http://poj.org/problem?id=2299
View Code
//POJ2299 int f_min(int x,int y) {if(x<y)return x; else return y;} int f_max(int x,int y) {if(x<y)return y; else return x;} const int MM = 511111; typedef __int64 int64; #define maxint 0x3f3f3f3f int64 N; int64 num[MM]; int64 L[MM], R[MM],ans; void get_data() { int64 i,j,k; for(i=1;i<=N;i++) scanf("%I64d",&num[i]); } int64 Merge(int64 *A,int64 p,int64 r,int64 q) { int64 i,j,k,len1,len2,ans; len1=r-p+1, len2=q-r; for(i=0;i<len1;i++) L[i]=A[p+i]; L[len1]=maxint; for(i=0;i<len2;i++) R[i]=A[r+1+i]; R[len2]=maxint; i=j=ans=0; for(k=p;k<=q;k++) { if(L[i]>R[j]) ans+=len1-i; if(L[i]<=R[j]) A[k]=L[i++]; else A[k]=R[j++]; } return ans; } int64 Merge_sort(int64*A,int64 p,int64 q) { int64 ret=0; if(p<q) { int64 mid=(p+q)>>1; ret+=Merge_sort(A,p,mid); ret+=Merge_sort(A,mid+1,q); ret+=Merge(A,p,mid,q); } return ret; } void solve() { int64 i,j,k; ans=Merge_sort(num,1,N); printf("%I64d\n",ans); } int main() { while(scanf("%d",&N),N) get_data(),solve(); return 0; }