poj2299 归并排序求逆序对

注意必须使用 long long 或 __int64

#include <cstdlib>
#include <iostream>
using namespace std;
long long ans;

void Merge( int a[], int tmpArray[], int l_sta, int r_sta, int r_end )
{
	int l_end = r_sta-1;
	int id = l_sta;
	int i,size = r_end-l_sta+1;

	while( l_sta <= l_end && r_sta <= r_end )
		if( a[l_sta] <= a[r_sta] )
			tmpArray[id++] = a[l_sta++];
		else {
			ans += l_end-l_sta+1;
			tmpArray[id++] = a[r_sta++];
		}
	while( l_sta <= l_end )
		tmpArray[id++] = a[l_sta++];
	while( r_sta <= r_end )
		tmpArray[id++] = a[r_sta++];

	for( i = 0; i < size; i++,r_end-- )
		a[r_end] = tmpArray[r_end];
}
void Msort( int a[], int tmpArray[], int left, int right )
{
	int center;

	if( left < right )
	{
		center = (left+right)/2;
		Msort( a, tmpArray, left, center );
		Msort( a, tmpArray, center+1, right );
		Merge( a, tmpArray, left, center+1, right );
	}
}
void MergeSort( int a[], int size )
{
	int *tmpArray;

	tmpArray = (int*)malloc( size*sizeof(int) );
	Msort( a, tmpArray, 0, size-1 );
	free( tmpArray );
}
int main()
{
	int a[500002];
	int n,i;
    
	while( scanf( "%d", &n ) && n )
	{
		for( i = 0; i < n; i++ )
  			scanf( "%d", &a[i] );
        ans = 0;
		MergeSort( a, n );
		printf( "%lld\n", ans );
	}
    return 0;
}


 

你可能感兴趣的:(merge)