POJ 2299 值域树状数组

In this problem, you have to analyze a particular sorting algorithm. The algorithm processes a sequence of n distinct integers by swapping two adjacent sequence elements until the sequence is sorted in ascending order. For the input sequence
9 1 0 5 4 ,

Ultra-QuickSort produces the output
0 1 4 5 9 .

Your task is to determine how many swap operations Ultra-QuickSort needs to perform in order to sort a given input sequence.

Input
The input contains several test cases. Every test case begins with a line that contains a single integer n < 500,000 – the length of the input sequence. Each of the the following n lines contains a single integer 0 ≤ a[i] ≤ 999,999,999, the i-th input sequence element. Input is terminated by a sequence of length n = 0. This sequence must not be processed.

Output
For every input sequence, your program prints a single line containing an integer number op, the minimum number of swap operations necessary to sort the given input sequence.

Sample Input
5
9
1
0
5
4
3
1
2
3
0

Sample Output
6
0

值域树状数组就是以值域建树。比如,一个数是 x , 那么我们建树的方法就是在x的地方加1.那么如何统计逆序对的个数呢?我们的方法就是插入每个数后,看在这个数之前插入的数中,有多少个数比它大,然后加入答案。

代码如下:

#include
#include
#include
#include
#define LL long long
using namespace std;
int a[500010],b[500010],c[500010],n;
int lowbit(int x){
    return x&(-x);
}
void add(int x,int val){
    while(x<=n){
        c[x]+=val;
        x+=lowbit(x);
    }
}
int query(int x){
    int s=0;
    while(x>0){
        s+=c[x];
        x-=lowbit(x);
    }
    return s;
}
int main(){
    while(scanf("%d",&n)!=EOF&&n){
        for(int i=1;i<=n;i++){
            scanf("%d",&a[i]);
            b[i]=a[i];
        }
        sort(a+1,a+n+1);
        for(int i=1;i<=n;i++)
            b[i]=lower_bound(a+1,a+n+1,b[i])-a;
        LL ans=0;
        memset(c,0,sizeof(c));
        for(int i=1;i<=n;i++){
            add(b[i],1);
            ans+=i-query(b[i]);
        }
        printf("%lld\n",ans);
    }
    return 0;
}

你可能感兴趣的:(树状数组)