HDU 1394 Minimum Inversion Number【树状数组求逆序】

Minimum Inversion Number
Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u

Description

The inversion number of a given number sequence a1, a2, ..., an is the number of pairs (ai, aj) that satisfy i < j and ai > aj. 

For a given sequence of numbers a1, a2, ..., an, if we move the first m >= 0 numbers to the end of the seqence, we will obtain another sequence. There are totally n such sequences as the following: 

a1, a2, ..., an-1, an (where m = 0 - the initial seqence) 
a2, a3, ..., an, a1 (where m = 1) 
a3, a4, ..., an, a1, a2 (where m = 2) 
... 
an, a1, a2, ..., an-1 (where m = n-1) 

You are asked to write a program to find the minimum inversion number out of the above sequences. 

Input

The input consists of a number of test cases. Each case consists of two lines: the first line contains a positive integer n (n <= 5000); the next line contains a permutation of the n integers from 0 to n-1. 

Output

For each case, output the minimum inversion number on a single line. 

Sample Input

10
1 3 6 9 0 8 5 7 4 2

Sample Output

16
 
    
思路:
先按之前的的方法求逆序,即结构体按数值从大到小排序,每次插入最大的元素到输入时的位置,并把该位赋值为1,
计算其左边比这个数大的数的个数(用树状数组求区间和从1到当前位置-1)累加就行;
求完一次逆序之后,其他的移动序列可以直接求出;
比如把a这个数移到最后面之后,大于他的数变成了n-1-a,也就是这个数的逆序增加了n-1-a,而其他数的逆序减少了a,
所以移动之后的逆序变化时原来的逆序加上n-1-a-a;多次累加就可;
 
    
代码:
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int c[5009];
int n;
struct node
{
	int val;
	int id;
}a[5009];
int cmp1(node x,node y)
{
	return x.val>y.val;
}
int cmp2(node x,node y)
{
	return x.id<y.id;
}
int lowbit(int x)
{
	return x&(-x);
}
void update(int x,int y)
{
	while(x<=n)
	{
		c[x]+=y;
		x+=lowbit(x);
	}
}
int getsum(int x)
{
	int s=0;
	while(x>0)
	{
		s+=c[x];
		x-=lowbit(x);
	} 
	return s;
} 
int main()
{
	while(scanf("%d",&n)!=EOF)
	{
		memset(c,0,sizeof(c));
		for(int i=1;i<=n;i++)
		{
			scanf("%d",&a[i].val);
			a[i].id=i;
		}
		sort(a+1,a+1+n,cmp1);
		int ans=0;//记录第一次求的逆序数; 
		for(int i=1;i<=n;i++)
		{
			update(a[i].id,1);//优先插入最大的;把当前最大的数插入到其输入时的位置; 
			ans+=getsum(a[i].id-1);//计算这个数所在的位置前面 有多少个数比他大; 
		}
		sort(a+1,a+1+n,cmp2); //序列又回到了原来的顺序; 
		int res=ans;//没有移动前的逆序数; 
		for(int i=1;i<=n;i++)
		{
			ans+=n-a[i].val-1-a[i].val;
			res=min(ans,res);//每次比较,不断更新; 
		}
		printf("%d\n",res);
	}
	return 0;
}


 
   
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值