可以用归并排序,也可以用树状数组!
下面提供两个代码!
AC代码如下:
归并排序!!
#include<iostream> #include<cstdio> #include<cstring> #define ll long long using namespace std; long long a[500005],b[500005]; long long sum; void GB(ll* A,int x,int y ,ll* T) { int i; if(y-x>1) { int m=x+(y-x)/2; int l=x,r=m,t=x; GB(A,x,m,T); GB(A,m,y,T); while(l<m||r<y) { if(r>=y||(l<m&&A[l]<=A[r])) T[t++]=A[l++]; else { T[t++]=A[r++]; sum+=m-l; } } for(i=x;i<y;i++) A[i]=T[i]; } } int main() { int n; int i,j; while(~scanf("%d",&n)&&n) { memset(b,0,sizeof b); for(i=0;i<n;i++) scanf("%lld",&a[i]); sum=0; GB(a,0,n,b); //for(i=0;i<n;i++) //cout<<a[i]<<" "; //cout<<endl; cout<<sum<<endl; } return 0; }
树状数组!!
#include<iostream> #include<cstdio> #include<cstring> #define M 1000100 using namespace std; long long c[M],num[M]; int l[M],n; long long lowbit(long long a) { return a&-a; } void add(long long a,int b) { while (a<M) { c[a]+=b; a+=lowbit (a); } } long long sum(long long a) { long long ans=0; while(a>0) { ans+=c[a]; a-=lowbit(a); } return ans; } int main () { int i,j; int a,b; while(~scanf("%d",&n)&&n) { memset(c,0,sizeof c); memset(num,0,sizeof num); int tt=0; for(i=1;i<=n;i++) { scanf("%lld",&num[i]); } long long ans=0; for(i=n;i>=1;i--) { if(num[i]==0) {l[i]=0;tt++;} else {l[i]=sum(num[i]-1)+tt; add(num[i],1);} ans=ans+(long long)l[i]; } printf("%lld\n",ans); } return 0; }
POJ 2299 Ultra-QuickSort,布布扣,bubuko.com
原文地址:http://blog.csdn.net/hanhai768/article/details/37818923