标签:
poj 2299 树状数组求逆序数
题目链接:http://poj.org/problem?id=2299
1 #include <stdio.h> 2 #include <string.h> 3 #include <iostream> 4 #include <algorithm> 5 #include <vector> 6 #include <queue> 7 #include <stack> 8 #include <set> 9 #include <map> 10 #include <string> 11 #include <math.h> 12 #include <stdlib.h> 13 using namespace std; 14 #define LL long long 15 struct node 16 { 17 LL v,id; 18 }p[500005]; 19 LL f[500005],n; 20 LL d[500005]; 21 bool cmp(node a,node b) 22 { 23 return a.v<b.v; 24 } 25 int lowbit(int x) 26 { 27 return x&(-x); 28 } 29 void update(int x) 30 { 31 while(x<=n) 32 { 33 f[x]++; 34 x+=lowbit(x); 35 } 36 return; 37 } 38 LL sum(int x) 39 { 40 LL s=0; 41 while(x) 42 { 43 s+=f[x]; 44 x-=lowbit(x); 45 } 46 return s; 47 } 48 int main() 49 { 50 LL i,j,k,m; 51 while(scanf("%lld",&n)!=EOF) 52 { 53 if(n==0) break; 54 memset(f,0,sizeof(f)); 55 memset(d,0,sizeof(d)); 56 for(i=1;i<=n;i++) 57 { 58 scanf("%lld",&p[i].v); 59 p[i].id=i; 60 } 61 sort(p+1,p+n+1,cmp); 62 for(i=1;i<=n;i++) 63 d[p[i].id]=i; 64 LL ans=0; 65 for(i=1;i<=n;i++) 66 { 67 update(d[i]); 68 ans+=(i-sum(d[i])); 69 } 70 printf("%lld\n",ans); 71 } 72 return 0; 73 }
标签:
原文地址:http://www.cnblogs.com/zuferj115/p/5001596.html