在一个排列中,如果一对数的前后位置与大小顺序相反,即前面的数大于后面的数,那么它们就称为一个逆序。一个排列中逆序的总数就称为这个排列的逆序数。
现在,给你一个N个元素的序列,请你判断出它的逆序数是多少。
比如 1 3 2 的逆序数就是1。
2 2 1 1 3 1 3 2
0 1
逆序数的对数可以看做冒泡排序时交换数的次数;
求解逆序数的思路戳链接: 将原数组排序后,按照排序后的数组的下标更新树状数组,这时候查询当前下标到他前边已经进入树状数组的所有数中比当前点小的数的个数sum(num[i].pos)
,然后用i-sum([i].pos)即是比当前点大的数的个数,将这个数累加;
#include<stdio.h>
#include<string.h>
#include<algorithm>
#define LL long long
using namespace std;
int m,n;
struct node 
{
	int val,pos;
}num[1001000];
bool cmp(node a,node b)
{
	if(a.val!=b.val)
	return a.val<b.val;
	else return a.pos<b.pos;
}
int c[2001000];
void update(int x)
{
	while(x<=n)
	{
		c[x]+=1;
		x+=x&-x;
	}
}
LL sum(int x)
{
	LL ans=0;
	while(x>=1)
	{
		ans+=c[x];
		x-=x&-x;
	}
	return ans;
}
int main()
{
	int j,i,t,k;
	scanf("%d",&t);
	while(t--)
	{
		scanf("%d",&n);
		for(i=1;i<=n;i++)
		{
			scanf("%lld",&num[i].val);
			num[i].pos=i;  //离散化,用下标更新; 
		}  
		sort(num+1,num+n+1,cmp);
		memset(c,0,sizeof(c));
		LL ant=0;
		for(i=1;i<=n;i++)
		{
			update(num[i].pos);
			ant+=i-sum(num[i].pos);
		}
		printf("%lld\n",ant);
	}
	return 0;
}
原文:http://www.cnblogs.com/tonghao/p/5409089.html