首页 > 代码库 > POJ2299 Ultra-QuickSort

POJ2299 Ultra-QuickSort

题解:

求逆序数裸题,

求逆序数,也就是把值放入树状数组中,而不是位置

值可能比较大,需要hash

代码:

#include<iostream>#include<cstring>#include<cstdio>#include<algorithm>#include<map>using namespace std;#define pb push_back#define mp make_pair#define se second#define fs first#define LL long long#define CLR(x) memset(x,0,sizeof x)#define lson l,m,rt<<1#define rson m+1,r,rt<<1|1 typedef pair<int,int> P;const double eps=1e-9;const int maxn=5010;const int mod=1e9+7;const int INF=1e9;int a[501000],b[501000],c[501000];map<int,int> m;int n;int lowbit(int x){return x&-x;}void Add(int x,int v){    while(x<=n){        c[x]+=v;        x+=lowbit(x);    }}int Sum(int x){    int sum=0;    while(x){        sum+=c[x];        x-=lowbit(x);    }    return sum;}int main(){    while(~scanf("%d",&n)&&n){        m.clear();        for(int i=1;i<=n;i++){            scanf("%d",&a[i]);            m[a[i]]=i;        }        sort(a+1,a+n+1);        for(int i=1;i<=n;i++) b[m[a[i]]]=i;        CLR(c);        LL sum=0;        for(int i=1;i<=n;i++){            sum+=Sum(n)-Sum(b[i]);            Add(b[i],1);        }        printf("%lld\n",sum);    }    return 0;}

 

POJ2299 Ultra-QuickSort