hdu1394 Minimum Inversion Number 树状数组

#include <stdio.h>
#include <string.h>
#define MAX 5005

int arr[MAX],n;
//树状数组
int lowBit(int x)//二进制后面为0的个数
{
	return (x&(-x));
}

void add(int index)
{
	while(index<=n)
	{
		arr[index]++;
		index+=lowBit(index);
	}
}

int func(int num)
{
	int sum=0;
	while(num>0)
	{
		sum+=arr[num];
		num-=lowBit(num);
	}
	return sum;
}

int main()
{
	int i,ans,min;
	int a[MAX];
	while(scanf("%d",&n)!=EOF)
	{
		ans=0;
		memset(arr,0,sizeof(arr));
		for(i=1;i<=n;i++)
		{
			scanf("%d",&a[i]);
			a[i]++;//a[i]从0开始,而树状数组下标从1开始,所以自增1
			add(a[i]);
			ans+=(i-func(a[i]));//求得的逆序对
		}
		min=ans;/*从后往前看,把a[n]移到第一位,逆序对增加a[i]-1,逆序对减少n-a[i]*/
		for (i=n;i>1;i--)
		{
			ans+=2*a[i]-1-n;
			min=ans<min?ans:min;
		}
		printf("%d\n",min);
	}
	return 0;
}

你可能感兴趣的:(hdu1394 Minimum Inversion Number 树状数组)