POJ 2299

逆序对的程序并没有错,错的是res的类型。下一次一定记得是long long了

 

#include <iostream> #define F(i,a,b) for (int i=a;i<=b;i++) using namespace std; int n[500002], c[500002], N; long long mergesort(int l, int r) { long long ret=0; if (l<r) { int mid=(l+r)/2; long long a=mergesort(l, mid); long long b=mergesort(mid+1, r); ret=a+b; int i=l, j=mid+1; int total=l; while(i<=mid && j<=r) { if (n[i]<=n[j]) c[total++]=n[i++]; else { c[total++]=n[j++]; ret+=mid-i+1; } } while (i<=mid) c[total++]=n[i++]; while (j<=r) c[total++]=n[j++]; F(i,l,r) n[i]=c[i]; } return ret; } int main() { //freopen ("in.txt", "r", stdin); while ( scanf("%d",&N) && N!=0 ) { F(i,1,N) scanf("%d", &n[i]); cout << mergesort(1,N) << endl; } return 0; }  

你可能感兴趣的:(POJ 2299)