(2012-07-21 15:10:02)
SOJ 2431: http://cstest.scu.edu.cn/soj/problem.action?id=2431
如题,利用归并排序求解逆序数。
SOJ 2431: http://cstest.scu.edu.cn/soj/problem.action?id=2431
如题,利用归并排序求解逆序数。
Code:
#include<iostream>
using namespace std;
int s[10005];
int result;
void merge(int low,int mid,int high)/合并。
{
int *t=new int[high+5];
int i,j,k;
for(i=low,j=mid+1,k=low;i<=mid && j<=high;k++)
{
if(s[i]<=s[j])
{
t[k]=s[i];
i++;
}
else
{
t[k]=s[j];
j++;
result=result+mid-i+1;
}
}
for(;i<=mid;i++,k++)
t[k]=s[i];
for(;j<=high;j++,k++)
t[k]=s[j];
for(i=low;i<=high;i++)
s[i]=t[i];
delete []t;
}
void merge_sort(int low,int high)
{
if(low<high)
{
int mid=(low+high)/2;
merge_sort(low,mid);
merge_sort(mid+1,high);
merge(low,mid,high);
}
}
int main()
{
int test;
scanf("%d",&test);
int n;
int i;
while(test--)
{
scanf("%d",&n);
result=0;
for(i=0;i<n;i++)
scanf("%d",&s[i]);
merge_sort(0,n-1);
printf("%d\n",result);//逆序数。
}
return 0;
}