【归并排序求逆序对个数】【树状数组求逆序对个数】
【AC】
1 #include<bits/stdc++.h> 2 using namespace std; 3 typedef long long ll; 4 5 const int maxn=1e5+2; 6 int a[maxn]; 7 int tmp[maxn]; 8 int n; 9 ll ans; 10 void Merge(int l,int m,int r) 11 { 12 int i=l,j=m+1; 13 int k=l; 14 while(i<=m&&j<=r) 15 { 16 if(a[i]<=a[j]) 17 { 18 tmp[k++]=a[i++]; 19 } 20 else 21 { 22 tmp[k++]=a[j++]; 23 ans+=(ll)(m-i+1); 24 } 25 } 26 while(i<=m) tmp[k++]=a[i++]; 27 while(j<=r) tmp[k++]=a[j++]; 28 for(int i=l;i<=r;i++) 29 { 30 a[i]=tmp[i]; 31 } 32 } 33 34 void Merge_Sort(int l,int r) 35 { 36 if(l<r) 37 { 38 int mid=(l+r)>>1; 39 Merge_Sort(l,mid); 40 Merge_Sort(mid+1,r); 41 Merge(l,mid,r); 42 } 43 } 44 int main() 45 { 46 while(~scanf("%d",&n)) 47 { 48 for(int i=0;i<n;i++) 49 { 50 scanf("%d",&a[i]); 51 } 52 ans=0; 53 Merge_Sort(0,n-1); 54 printf("%lld\n",ans); 55 } 56 return 0; 57 }
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<string> 5 #include<cmath> 6 #include<algorithm> 7 using namespace std; 8 typedef long long ll; 9 const int maxn=5e5+2; 10 11 int n; 12 ll ans; 13 struct node 14 { 15 int x; 16 int pos; 17 }a[maxn]; 18 int tree[maxn]; 19 int r[maxn]; 20 bool cmp(node nd1,node nd2) 21 { 22 return nd1.x<nd2.x; 23 } 24 int lowbit(int x) 25 { 26 return x&-x; 27 } 28 void add(int k,int x) 29 { 30 while(k<=n) 31 { 32 tree[k]+=x; 33 k+=lowbit(k); 34 } 35 } 36 ll query(int k) 37 { 38 ll ans=0; 39 while(k) 40 { 41 ans+=tree[k]; 42 k-=lowbit(k); 43 } 44 return ans; 45 } 46 int main() 47 { 48 while(scanf("%d",&n)&&n) 49 { 50 for(int i=1;i<=n;i++) 51 { 52 scanf("%d",&a[i].x); 53 a[i].pos=i; 54 } 55 sort(a+1,a+n+1,cmp); 56 for(int i=1;i<=n;i++) 57 { 58 r[a[i].pos]=i; 59 } 60 memset(tree,0,sizeof(tree)); 61 ans=0; 62 for(int i=1;i<=n;i++) 63 { 64 add(r[i],1); 65 ans+=i-query(r[i]); 66 } 67 cout<<ans<<endl; 68 } 69 return 0; 70 }