hdu 1394 Minimum Inversion Number

来源:互联网 发布:mysql 视图 union all 编辑:程序博客网 时间:2024/06/16 13:22

Minimum Inversion Number

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


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

题意:
     给你一个数列。你可以将前m个元素移动到末尾。(m<=n-1)问你这个数列可以得到的最小逆序数。
思路:
     逆序数就不解释了。由于题目中数组中的数都是连续的且规模不大所以就不用离散化了。
首先要知道求一个固定数组的逆序数的算法。用树状数组实现就是将数组中的元素按序号插入。
然后就用已插入的元素个数i-比当前插入元素小的元素个数。剩下的自然是角标比a[i]小但值比a[i]大的元素个数了。
因为逆序数即标号小的数的值比标号大的数大。所以可以先update(a[i])将a[i]插入用i-getsum(a[i])来计算。
getsum(a[i])此时只有先插入的元素及角标小的元素而getsum(a[i])是算c[1]到c[i]的和即比a[i]小的元素个数。
后面就要解决如何移动前面元素到加到后面使逆序对数最小了。
一下子移动几个不是那么好计算。于是想到一个一个移动,
因为一下子移动几个可以由一下子移动一个得来。
用一个循环就行。考虑把当前第一个元素移动到数组的尾部。那么会对逆序数ans造成什么影响呢?
由于元素的值是连续的。把当前第一个数移动到尾部必然增加n-a[i]个逆序数。
因为前面一定有n-a[i]比自己大。
还会造成以前已有的逆序数减少。因为以前在a[i]后面还有a[i]-1个元素比自己小当a[i]移动到尾部后。这部分逆序数将消失。
所以逆序数改变为n-a[i]-(a[i]-1)。即n-2*a[i]+1。
详细见代码:
 
#include <iostream>#include<stdio.h>#include<string.h>#include<algorithm>using namespace std;int a[5010],c[5010];int n;int lowbit(int x){    return x&(-x);}void update(int x){    while(x<=n)    {        c[x]+=1;        x+=lowbit(x);    }}int getsum(int x){    int sum=0;    while(x>0)    {        sum+=c[x];        x-=lowbit(x);    }    return sum;}int main(){    int i;    long long ans,mi;    while(~scanf("%d",&n))    {        memset(c,0,sizeof c);        ans=0;        for(i=1;i<=n;i++)        {            scanf("%d",a+i);            a[i]++;//a[i]不能为0不然更新时会出现死循环            update(a[i]);            ans+=i-getsum(a[i]);//i-角标小且值小的数即不满足逆序数的数            //cout<<"ok"<<endl;        }        mi=ans;        for(i=1;i<=n;i++)        {            ans+=n-a[i]+1-a[i];//由于从第一个变为最后一个(关键!!)所以增加比a[i]大个逆序数减少比a[i]小个逆序数。即ans+=n-a[i]+1-a[i]            if(ans<mi)                mi=ans;        }        printf("%I64d\n",mi);    }    return 0;}