树状数组求逆序数
poj 2299 树状数组求逆序数
题目链接:http://poj.org/problem?id=2299
#include <stdio.h> #include <string.h> #include <iostream> #include <algorithm> #include <vector> #include <queue> #include <stack> #include <set> #include <map> #include <string> #include <math.h> #include <stdlib.h> using namespace std; #define LL long long struct node { LL v,id; }p[500005]; LL f[500005],n; LL d[500005]; bool cmp(node a,node b) { return a.v<b.v; } int lowbit(int x) { return x&(-x); } void update(int x) { while(x<=n) { f[x]++; x+=lowbit(x); } return; } LL sum(int x) { LL s=0; while(x) { s+=f[x]; x-=lowbit(x); } return s; } int main() { LL i,j,k,m; while(scanf("%lld",&n)!=EOF) { if(n==0) break; memset(f,0,sizeof(f)); memset(d,0,sizeof(d)); for(i=1;i<=n;i++) { scanf("%lld",&p[i].v); p[i].id=i; } sort(p+1,p+n+1,cmp); for(i=1;i<=n;i++) d[p[i].id]=i; LL ans=0; for(i=1;i<=n;i++) { update(d[i]); ans+=(i-sum(d[i])); } printf("%lld\n",ans); } return 0; }