H

在一个排列中,如果一对数的前后位置与大小顺序相反,即前面的数大于后面的数,那么它们就称为一个逆序。一个排列中逆序的总数就称为这个排列的逆序数。

如2 4 3 1中,2 1,4 3,4 1,3 1是逆序,逆序数是4。给出一个整数序列,求该序列的逆序数。

Input

第1行:N,N为序列的长度(n <= 50000) 
第2 - N + 1行:序列中的元素(0 <= Aii <= 10^9)

Output

输出逆序数

Sample Input

4
2
4
3
1

Sample Output

4

思路:暴力的思路大约是n^2,可以用树状数组来优化

代码:

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
 
#define MAXN 50005

using namespace std;

int tree[MAXN], n;

int lowbit(int x){ 
    return x&(-x);
}

void update(int x, int d){ 
    while(x<=n){
        tree[x]+=d;
        x+=lowbit(x);
    }
}

int sum(int x){ 
    int ans=0;
    while(x>0){
        ans+=tree[x];
        x-=lowbit(x);
    }
    return ans;
}

int main(void){
    pair<int, int> p[MAXN];
    int gg[MAXN], ans=0;
    scanf("%d", &n);
    for(int i=1; i<=n; i++){  
        scanf("%d", &p[i].first);
        p[i].second=i;
    }
    sort(p+1, p+n+1);
    for(int i=1; i<=n; i++){
        gg[p[i].second]=i;
    }
    for(int i=1; i<=n; i++){
        update(gg[i], 1); 
        ans+=i-sum(gg[i]);
    }
    printf("%d
", ans);
    return 0;
}
原文地址:https://www.cnblogs.com/Staceyacm/p/10781853.html