http://poj.org/problem?id=2299
归并虽然知道了过程但是敲起代码来还是出现各种小错误。。。唉,,,
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
#include <cstdio>
#include <iostream>
#define maxn 500007
using namespace std;
int a[maxn];
int n;
int tmp[maxn];
__int64 ct;
void merge(int s,int m,int e)
{
int i = s,j = m + 1;
int k = 0;
while (i <= m && j <= e)
{
//s - m 和 m+1 —— e两个数组是已经排好序的
//如果a[i] > a[j]则说明i - m的值都大于a[j]出现逆序数
if (a[i] > a[j])
{
ct += m - i + 1;
tmp[k++] = a[j++];
}
else
{
tmp[k++] = a[i++];
}
}
while (i <= m)
tmp[k++] = a[i++];
while (j <= e)
tmp[k++] = a[j++];
for (i = 0; i < k; ++i)
{
a[s + i] = tmp[i];
}
}
void mergesort(int s,int e)
{
if (s < e)
{
int m = (s + e)/2;
mergesort(s,m);
mergesort(m + 1,e);
merge(s,m,e);
}
}
int main()
{
int i;
while (~scanf("%d",&n))
{
if (!n) break;
ct = 0;
for (i = 0; i < n; ++i)
scanf("%d",&a[i]);
mergesort(0,n - 1);
printf("%I64d\n",ct);
}
return 0;
}