POJ2299 归并求逆序数

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
#define mxn 500040
#define ll long long
ll cnt;
void merge_sort( int * A, int x, int y, int * T ) {
	if( y - x > 1 ) {
		int m = x + ( y - x ) / 2;
		int p = x, q = m, i = x;
		merge_sort( A, x, m, T );
		merge_sort( A, m, y, T );
		while( p < m || q < y ) {
			if( q >= y || ( p < m && A[p] <= A[q] ) )
				T[i++] = A[p++];
			else {
				T[i++] = A[q++];
				cnt += m - p;
			}
		}
		for( int j = x; j < y; ++j ) {
			A[j] = T[j];
		}
	}
}
int a[mxn];
int T[mxn];
int main() {
	int n;
	while( scanf( "%d", &n ) && n ) {
		cnt = 0;
		for( int i = 1; i <= n; ++i ) {
			scanf( "%d", &a[i] );
		}
		merge_sort( a, 1, n + 1, T );
		printf( "%I64d\n", cnt );
	}
	return 0;
}

你可能感兴趣的:(POJ2299 归并求逆序数)