POJ 1394 Minimum Inversion Number

Minimum Inversion Number

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 23666    Accepted Submission(s): 14042


 

Problem 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

 

Author

CHEN, Gaoli

 

Source

ZOJ Monthly, January 2003

 

Recommend

Ignatius.L

 

题目大意:求循环移位后逆序数的最小值

题目总是把第一个数移到最后一个位置 所以原来和他构成逆元的数 在移动之后就不是逆元了,而原来比他大的数 在移动以后就是逆元了 sum=sum-(low[a[i]])+(up[a[i]);

(逆序数求得之后,把第一个数移到最后的逆序数是可以直接得到的。 比如原来的逆序数是ans,把a[0]移到最后后,减少逆序数a[0],同时增加逆序数n-a[0]-1个 就是ans-a[0]+n-a[0]-1;)

#include <iostream>
#include <cstring>
#include <cstdio>
#include <string>
#include <algorithm>
#include <cmath>
using namespace std;
const int maxn=101111;
struct node
{
	int l,r;
	int sum;
}Segtree[maxn*4];
void build(int rt,int l,int r)
{
	Segtree[rt].l=l;
	Segtree[rt].r=r;
	if(l==r)
	{
		Segtree[rt].sum=0;
		return ;
	}
	int mid=(l+r)>>1;
	build(rt<<1,l,mid);//左 
	build(rt<<1|1,mid+1,r);//右
	Segtree[rt].sum=0; 
}
void add(int rt,int t,int val)
{
	Segtree[rt].sum+=val;
	if(Segtree[rt].l==Segtree[rt].r)
	{
		return;
	}
	int mid=(Segtree[rt].l+Segtree[rt].r)>>1;
	if(t<=mid) add(rt<<1,t,val);
	else add((rt<<1)|1,t,val);
}
int sum(int rt,int l,int r)
{
	if(Segtree[rt].l==l&&Segtree[rt].r==r)
	return Segtree[rt].sum;
	int mid=(Segtree[rt].l+Segtree[rt].r)>>1;
	if(r<=mid) return sum(rt<<1,l,r);//左子树 
	else if(l>mid) return sum((rt<<1)|1,l,r);//右子树
	else return sum(rt<<1,l,mid)+sum((rt<<1)|1,mid+1,r); 
}
int a[maxn];
int main()
{
	int n;
	while(scanf("%d",&n)!=EOF)
	{
		build(1,0,n-1);
		for(int i=0;i<n;i++)
		{
			scanf("%d",&a[i]);
		 } 
		 int ans=0;
		for(int i=0;i<n;i++)
		{
			ans+=sum(1,a[i],n-1);
			add(1,a[i],1);
		}
		int Min=ans;
		for(int i=0;i<n;i++)
		{
			ans-=a[i];//减少的逆序数
			ans+=n-a[i]-1;//增加的逆序数
			if(ans<Min) Min=ans; 
		}
		printf("%d\n",Min);
	}return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40046426/article/details/81235910