ZOJ 1484 Minimum Inversion Number(2007-07-30 20:45)

来源:互联网 发布:淘宝网上卖东西会骗吗 编辑:程序博客网 时间:2024/05/22 15:33
 

被某人拉去ZOJ帮做题...一开始写了个O(n^2)的, 华丽地TLE掉...貌似常数太大. 后来发现没利用好题目的条件, 再写了个也是O(n^2)的AC了, 貌似是130MS, 不大会看ZOJ的时间......好像最前面是分钟.

题目:

Minimum Inversion Number

Time limit: 1 Seconds   Memory limit: 32768K   
Total Submit: 1453   Accepted Submit: 729   

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

设num为逆序数,w[i]为第i个数字

N种排列中选一种, 它的逆序数最小. 输出这个最小逆序数.

现在的做法是先O(n^2)求出最初的逆序数, 然后不断地把最后一个数插到最前面, 再计算一下逆序数的变化. 具体的方法就是: num-=n-1-w[n-1]; num+=w[n-1]

理由 : 把最后面的数字插入最前面, 所有原来的w[i](i<n-1且w[i]>w[n-1])就不再具有i<n-1且w[i]>w[n-1]的关系. 由题意可知道刚好有n-1-w[n-1]个. (数字是0~n-1). num+=w[n-1]同理

每次改变排列就更新一下最小值,最后输出即可.

计算逆序数这地方应该是可以优化的吧...暂时也没想到.

代码:

  1. #include "stdio.h"
  2. const int maxn=5001;
  3. int num[maxn];
  4. int main(){
  5.       int n;
  6.       while(scanf("%d",&n)!=EOF){
  7.           int i;
  8.           for(i=0;i< n;++i){
  9.               scanf("%d",&num[i]);
  10.           }
  11.           int sum=0;
  12.           int min;
  13.           int j;
  14.           for(i=0;i< n;++i){
  15.               for(j=i+1;j< n;++j){
  16.                   sum+=(num[i]>num[j]);
  17.               }
  18.           }
  19.           min=sum;
  20.           for(i=n-1;i>0;--i){
  21.               sum-=n-1;
  22.               sum+=(num[i]<< 1);
  23.               if(sum< min){
  24.                   min=sum;
  25.               }
  26.           }
  27.           printf("%d/n",min);
  28.       }
  29.       return 0;
  30. }