POJ 2299 Ultra-QuickSort(归并排序)

Description
求序列的逆序对
Input
多组输入,每组用例第一行为序列长度n,之后n行为序列,以n=0结束输入
Output
对于每组用例,输出该序列的逆序对数
Sample Input
5
9
1
0
5
4
3
1
2
3
0
Sample Output
6
0
Solution
归并排序求逆序对即可
Code

#include<stdio.h>
#define maxn 500005
typedef long long ll;
int n,a[maxn],temp[maxn];
ll count;
void MergSort(int low,int high)  
{  
    int i,j;  
    if(low<high)  
    {  
        int k=0;  
        int mid=(high+low)/2;  
        MergSort(low,mid);  
        MergSort(mid+1,high);  
        for(i=low,j=mid+1;i<=mid&&j<=high;)  
        {  
            if(a[i]>a[j])  
                temp[k++]=a[j++];  
            else  
            {  
                count+=j-mid-1;  
                temp[k++]=a[i++];  
            }  
        }  
        while(i<=mid)  
        {  
            count+=j-mid-1;  
            temp[k++]=a[i++];  
        }  
        while(j<=high)  
            temp[k++]=a[j++];  
        j=low;  
        for(i=0;i<k;i++)  
            a[j++]=temp[i];  
    }  
} 
int main()
{
    while(scanf("%d",&n),n!=0)
    {
        count=0;
        for(int i=0;i<n;i++)
            scanf("%d",&a[i]);
        MergSort(0,n-1);  
        printf("%lld\n",count);  
    }
    return 0;
}

你可能感兴趣的:(POJ 2299 Ultra-QuickSort(归并排序))