http://poj.org/problem?id=2299
题目大意:给一串数,求其按照两两交换排序最少排几次。
求逆序对裸题,不建议用数据结构(因为需要离散化)
#include<cstdio> #include<cmath> #include<algorithm> #include<cstring> #include<iostream> using namespace std; typedef long long ll; ll n,a[500001],t[500001]; ll ans = 0; void msort(int x,int y) { if(x==y) return; int mid = (x + y) >>1; msort(x,mid); msort(mid+1,y); int l = x, r = mid+1, j = x; while(l<=mid && r<=y) { if(a[l]<=a[r]){ t[j] = a[l]; j++;l++; } else{ t[j] = a[r]; r++;j++; ans += mid-l+1; } } while(l<=mid){ t[j] = a[l]; j++;l++; } while(r<=y){ t[j] = a[r]; r++;j++; } for(int i=x;i<=y;i++)a[i] = t[i]; return; } int main(){ while(scanf("%lld",&n)!=EOF){ if(!n)return 0; ans=0; for(int i=1;i<=n;i++){ scanf("%lld",&a[i]); } msort(1,n); printf("%lld ",ans); } return 0; }