树状数组求逆序对

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<vector>
#include<queue>
#include<stack>
#define lowbit(x) x&(-x)
using namespace std;
struct data
{
    int pos,val;
    bool operator<(const data a)const
    {
        return val<a.val;
    }
}a[551000];
int aa[551000];
int c[551000],n,cnt;
inline int sum(int x)
{
    int res=0;
    for(int i=x;i>=1;i-=lowbit(i))res+=c[i];
    return res;
}
inline void add(int x)
{
    for(int i=x;i<=n;i+=lowbit(i))c[i]++;
}
long long ans;
int main()
{
    while(~scanf("%d",&n) && n)
    {
        ans=0;
        memset(c,0,sizeof(c));
        for(int i=1;i<=n;i++)
        {
            scanf("%d",&a[i].val);
            a[i].pos=i; 
        }
        sort(a+1,a+n+1);
        cnt=1;
        for(int i=1;i<=n;i++)aa[a[i].pos]=i;
        for(int i=1;i<=n;i++)
        {
            ans+=i-sum(aa[i])-1;
            add(aa[i]);
        } 
        printf("%lld\n",ans);
    }
    return 0;
}
View Code

 

posted @ 2017-10-31 16:37  探险家Mr.H  阅读(152)  评论(0编辑  收藏  举报