http://poj.org/problem?id=2299
归并排序
代码:
#include<iostream> #include<stdio.h> #include<string.h> #include<math.h> #include<algorithm> #include<vector> #include<set> #include<map> #include<string> #include<queue> #include<stack> #include <iomanip> using namespace std; #define LL long long #define sint short int const int INF=0x3f3f3f3f; //priority_queue<int,vector<int>,greater<int> >qt; const int N=500005; int a[N],b[N]; LL ans; void mysort(int l,int r) { if(l==r) return ; int mid=(l+r)>>1; mysort(l,mid); mysort(mid+1,r); int i,j,k=l; for(i=l,j=mid+1;i<=mid||j<=r;++k) { if(i>mid) {b[k]=a[j];++j;continue;} if(j>r) {b[k]=a[i];++i;continue;} if(a[i]<a[j]) {b[k]=a[i];++i;} else {b[k]=a[j];ans=ans+(LL)(j-k);++j;} } for(int x=l;x<=r;++x) a[x]=b[x]; return ; } int main() { //freopen("data.in","r",stdin); int n; while(scanf("%d",&n)!=EOF,n) { for(int i=0;i<n;++i) scanf("%d",&a[i]); ans=0; mysort(0,n-1); cout<<ans<<endl; } return 0; }