POJ2299 树状数组求逆序对
裸题,不多解释。
1 #include<iostream> 2 #include<cstdio> 3 #include<algorithm> 4 #include<cstring> 5 using namespace std; 6 #define maxn 500005 7 int a[maxn],b[maxn],c[maxn]; 8 int n; 9 long long ans; 10 int lowbit(int x){ 11 return x&(-x); 12 } 13 void updata(int x){ 14 for(int i=x;i<=n;i+=lowbit(i)) 15 c[i]+=1; 16 } 17 int ask(int x){ 18 int tot=0; 19 for(int i=x;i>=1;i-=lowbit(i)) 20 tot+=c[i]; 21 return tot; 22 } 23 int main(){ 24 while(scanf("%d",&n),n){ 25 int cnt=0; 26 for(int i=1;i<=n;i++){ 27 scanf("%d",&a[i]); 28 b[i]=a[i]; 29 } 30 ans=0; 31 sort(a+1,a+n+1); 32 cnt=unique(a+1,a+n+1)-a-1; 33 memset(c,0,sizeof c); 34 for(int i=1;i<=n;i++){ 35 b[i]=lower_bound(a+1,a+cnt+1,b[i])-a; 36 updata(b[i]); 37 ans+=i-ask(b[i]); 38 } 39 printf("%I64d\n",ans); 40 } 41 }