HDU1394

Minimum Inversion Number

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


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

题意:先输入一个n代表有n个数,然后输入n个数(0~n-1),可以把第一个数移到最后形成新的数列,问最小的逆序数是多少。
逆序数: 也就是说,对于n个不同的元素,先规定各元素之间有一个标准次序(例如n个 不同的 自然数 ,可规定从小到大为标准次序),于是在这n个元素的任一排列中,当某两个元素的先后次序与标准次序不同时,就说有1个逆序。一个排列中所有逆序总数叫做这个排列的逆序数。
(一开始读完题完全不知道逆序数是啥东西,看别人博客看了很久,结构搜了一下逆序数的概念发现可以直接暴力.)
先求出题目给出的逆序数,然后用递推关系求得将第一个数移到最后形成的新的数列的逆序数. sum=sum-a[i]+(n-a[i]-1)。
将第一个数移到最后可以看成两步:
(1):将第一个数从数列中移除,会发现逆序数减少了a[1](当前数列的第一个数)。
(2):将第一个数加入到数列的最后,会发现此时的逆序数在(1)的基础上 +n-a[1]-1。
所以就可以得出递推关系了。

#include<stdio.h>
#include<string.h>
int a[5010],b[5010];
int main()
{
    int i,j,k,n,s,sum;
    while(scanf("%d",&n)!=EOF)
    {
        for(i=0;i<n;i++)
            scanf("%d",&a[i]);
        memset(b,0,sizeof(b));
        s=0;
        for(i=1;i<n;i++)
        {
            k=0;
            for(j=0;j<i;j++)
            {
                if(a[i]<a[j])
                    k++;
            }
            b[i]=k;
            s=s+k;
        }
        sum=s;
        for(i=0;i<n;i++)
        {
            sum=sum-a[i]+(n-a[i]-1);
            if(sum<s)
                s=sum;
        }
        printf("%d\n",s);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_37751662/article/details/70300446