题目链接: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
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
Output
Sample Input
1 3 6 9 0 8 5 7 4 2
Sample Output
题解
题意:一个由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 ;
}