#include<stdio.h> long long cnt; long long a[500001],t[500001]; void merge(long long *a,long long *t,int l,int m,int r) { int p = l; int q = m+1; int k = p; while(p <= m||q <= r) { if(q > r||(p <= m&&a[p] <= a[q])) t[k++] = a[p++]; else { cnt += m-p+1; t[k++]=a[q++]; } } for(int i = l; i <= r; i++)a[i]=t[i]; } void mergesort(long long *a,long long *t,int l,int r) { if(r > l) { int m = (l+r)/2; mergesort(a,t,l,m); mergesort(a,t,m+1,r); merge(a,t,l,m,r); } } int main() { int n; while(~scanf("%d", &n)) { if(n==0) break; cnt = 0; for(int i = 0; i < n; i++) scanf("%lld", &a[i]); mergesort(a,t,0,n-1); printf("%lld\n", cnt); } return 0; }
时间: 2024-10-26 05:49:13