您的位置:首页 > 其它

POJ 1394 Minimum Inversion Number

2016-04-21 18:59 363 查看
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): 12139    Accepted Submission(s): 7411


[align=left]Problem Description[/align]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.
 
[align=left]Input[/align]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.
 
[align=left]Output[/align]For each case, output the minimum inversion number on a single line.
 
[align=left]Sample Input[/align]
10
1 3 6 9 0 8 5 7 4 2 
[align=left]Sample Output[/align]
16 
[align=left]Author[/align]CHEN, Gaoli 
[align=left]Source[/align]ZOJ Monthly, January 2003 
[align=left]Recommend[/align]Ignatius.L题目大意:给定一个0到n-1的数字组成的序列,求它的逆序数,然后把第一个数字放到末尾,得到一个新的序列,再求逆序数,再把新序列的第一个数字放到末尾,一直这样做,求所有这些序列的逆序数的最小值。树状数组求逆序数。代码如下
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdlib>
#include<vector>
#include<cmath>
#include<stdlib.h>
#include<iomanip>
#include<list>
#include<deque>
#include<map>
#include <stdio.h>
#include <queue>
#include <stack>
#define maxn 10000+5
#define ull unsigned long long
#define ll long long
#define reP(i,n) for(i=1;i<=n;i++)
#define rep(i,n) for(i=0;i<n;i++)
#define cle(a) memset(a,0,sizeof(a))
#define mod 90001
#define PI 3.141592657
#define INF 1<<30
const ull inf = 1LL << 61;
const double eps=1e-5;

using namespace std;

bool cmp(int a,int b){
return a>b;
}
int a[5002];
int c[5002];
int n,Sum;
int lowbit(int i)
{
return i&(-i);
}
void add(int i,int d)
{
while(i<=n)
{
c[i]+=d;
i+=lowbit(i);
}
}
int sum(int i)
{
int ret=0;
while(i>=1)
{
ret+=c[i];
i-=lowbit(i);
}
return ret;
}
int main()
{
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
while(~scanf("%d",&n))
{
cle(c);
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
Sum=0;
for(int i=1;i<=n;i++)
{
add(a[i]+1,1);
Sum+=i-sum(a[i]+1);//i代表个数的意思
}
int ans=INF;
for(int i=1;i<=n;i++)
{
Sum+=(n-1-2*a[i]);
ans=min(ans,Sum);
}
printf("%d\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: