首页 > 代码库 > HDU 1394 Minimum Inversion Number ( 树状数组求逆序数 )

HDU 1394 Minimum Inversion Number ( 树状数组求逆序数 )

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1394

                              Minimum Inversion Number

 

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


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

101 3 6 9 0 8 5 7 4 2
 

 

Sample Output

16
 

 

Author
CHEN, Gaoli
 

 

Source
ZOJ Monthly, January 2003
 

 

Recommend
Ignatius.L   |   We have carefully selected several similar problems for you:  1166 1698 1540 1542 1255 
 

题解

题意:一个由0..n-1组成的序列,每次可以把队首的元素移到队尾,求形成的n个序列最小逆序对数目


算法:
由树状数组求逆序对。加入元素i即把以元素i为下标的a[i]+1,从队尾到队首入队,
每次入队时逆序对数 += getsum(i - 1),即下标比它大的但是值比它小的元素个数。
因为树状数组不能处理下标为0的元素,每个元素进入时+1,相应的其他程序也要相应调整。
求出原始的序列的逆序对个数后每次把最前面的元素移到队尾,逆序对数即为

原逆序对数+i大的元素个数-i小的元素个数,因为是0..n,容易直接算出,每次更新min即可。

 

 

 1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<algorithm> 5  6 using namespace std; 7  8 const int N=5010; 9 10 int n,arr[N],num[N];11 12 int lowbit(int x)13 {14     return x&(-x);15 }16 17 void update(int id,int x)18 {19     while(id<=N)20     {21         arr[id]+=x;22         id+=lowbit(id);23     }24 }25 26 int Sum(int id)27 {28     int ans=0;29     while(id>0)30     {31         ans+=arr[id];32         id-=lowbit(id);33     }34     return ans;35 }36 37 int min(int x,int y)38 {39     return x>y?y:x;40 }41 42 int main()43 {44     while(scanf("%d",&n)!=EOF)45     {46         memset(arr,0,sizeof(arr));47         int i,ans=0;48         for(i=1;i<=n;i++)49         {50             scanf("%d",&num[i]);51             ans+=Sum(n+1)-Sum(num[i]+1);52             update(num[i]+1,1);53         }54         int tmp=ans;55         for(i=1;i<=n;i++)56         {57             tmp+=n-1-num[i]-num[i];58             ans=min(ans,tmp);59         }60         printf("%d\n",ans);61     }62     return 0;63 }
View Code