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

10
1 3 6 9 0 8 5 7 4 2
 

Sample Output

16
 
Author
CHEN, Gaoli
 
Source
 
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即可。

 #include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm> using namespace std; const int N=; int n,arr[N],num[N]; int lowbit(int x)
{
return x&(-x);
} void update(int id,int x)
{
while(id<=N)
{
arr[id]+=x;
id+=lowbit(id);
}
} int Sum(int id)
{
int ans=;
while(id>)
{
ans+=arr[id];
id-=lowbit(id);
}
return ans;
} int min(int x,int y)
{
return x>y?y:x;
} int main()
{
while(scanf("%d",&n)!=EOF)
{
memset(arr,,sizeof(arr));
int i,ans=;
for(i=;i<=n;i++)
{
scanf("%d",&num[i]);
ans+=Sum(n+)-Sum(num[i]+);
update(num[i]+,);
}
int tmp=ans;
for(i=;i<=n;i++)
{
tmp+=n--num[i]-num[i];
ans=min(ans,tmp);
}
printf("%d\n",ans);
}
return ;
}
 
上一篇:CocoaPods安装和使用


下一篇:MySQL 千万 级数据量根据(索引)优化 查询 速度