Ultra-QuickSort POJ - 2299 树状数组求逆序对

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
typedef long long ll;
const int N=5e5+10;
int n;
int a[N];
int tr[N];
int b[N];
int c[N]; 
int lowbit(int x)
{
    return x&-x;
}
void add(int x,int c)
{
    for(int i=x;i<=n;i+=lowbit(i))
        tr[i]+=c;
}
int sum(int x)
{
    int res=0;
    for(int i=x;i;i-=lowbit(i))
        res+=tr[i];
    return res;
}
int main()
{
    while(cin>>n,n)
    {
        for(int i=1;i<=n;i++)
        {
            cin>>a[i];
            b[i]=a[i];
        }
        //最终的位置 
        sort(b+1,b+1+n);
        //a中元素在b中的位置,然后放到c中 
        //a中元素1~n   应该在的位置 
        
        //相当于离散化 
        for(int i=1;i<=n;i++)
            c[i]=lower_bound(b+1,b+1+n,a[i])-b;
        memset(tr,0,sizeof tr);
        ll ans=0;
        for(int i=1;i<=n;i++)
        {
            add(c[i],1);
            ans+=i-sum(c[i]);
        } 
        cout<<ans<<endl;
    }
}

猜你喜欢

转载自www.cnblogs.com/QingyuYYYYY/p/12285709.html