题目:点击打开链接
这个题给出了500000个样例组,数据最大到1E,求这一串序列的逆序数。逆序数的定义不多说,详见线性代数。
表示有好几种方法可以解决这个问题,如树状数组、线段树、归并排序等。
归并排序是最接近模板法的,因为排序的结构决定了它是在相邻两个数之间进行的比较。很容易MLE的,如果数组开的过大或者过小的话。部分参阅了标准模板。
/**** **** **** **** **** ****
* Function Name : 逆序数(归并排序)
* Description : N*Log(N)
**** **** **** **** **** ****/
//逆序数值存放在anti中
//待排序数组为p.
#include <iostream>
#include <stdio.h>
#include <cstring>
using namespace std;
const __int64 MAX=3000000;
__int64 p[MAX], t[MAX];
__int64 anti = 0;
void merge(int first, int last)
{
int mid = (first+last)/2;
int i1 = 0, i2 = first, i3 = mid+1;
while (i2 <= mid && i3 <= last)
{
if (p[i2] > p[i3])
{
t[i1++] = p[i3++];
anti += mid-i2+1;
}
else t[i1++]=p[i2++];
}
while (i2 <= mid)
t[i1++] = p[i2++];
while (i3 <= last)
t[i1++] = p[i3++];
i1 = first;
i2 = 0;
while (i2 < last-first+1) p[i1++] = t[i2++];
}
void merge_sort(int first, int last)
{
int mid;
if (first<last)
{
mid = (first+last)/2;
merge_sort(first, mid);
merge_sort(mid+1, last);
merge(first, last);
}
}
int main()
{
int testcase;
while(cin>>testcase && testcase!=0)
{
memset(p,0,sizeof(p));
memset(t,0,sizeof(t));
anti=0;
for(int i=1;i<=testcase;i++)
{
scanf("%d",&p[i]);
}
merge_sort(1,testcase); //注意要加1
printf("%I64d\n",anti);
}
return 0;
}