Minimum Inversion Number

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

给你0--n-1一共n个数,现在序列中的第1个放到序列的最后,构成包含输入序列在内
的n个序列问这n个序列中,逆序对最少的是多少。

只要先把第一个序列的逆序和sum计算出来,发现在将a[i]移动到最后后形成的
序列中逆序的数量为sum=sum-a[i]+n-1-a[i];

在计算第一个序列的逆序对过程中可以用暴力,也可以用线段树。
#include<stdio.h>
int a[10000];
struct haha
{
    int left;
    int right;
    int num;
}node[10000*4];
void build(int left,int right,int nd)//nd为根节点
{
    node[nd].left=left;
    node[nd].right=right;
    node[nd].num=0;
    if(left==right) 
    {
        return ;
    }
    int mid=(left+right)/2;
    build(left,mid,nd*2);
    build(mid+1,right,nd*2+1);
}
int query(int left,int right,int nd)
{
    int mid=(node[nd].left+node[nd].right)/2;
    if(node[nd].left==left&&node[nd].right==right)
    {
        return node[nd].num;
    }
 
    if(right<=mid)
    {
          return query(left,right,nd*2);
    }
    else if(left>mid)
    {
        return query(left,right,nd*2+1);
    }
    else
    {
        return query(left,mid,nd*2)+query(mid+1,right,nd*2+1);
    }
}
void update(int pos,int nd)///将包含pos的各个区间中pos出现的次数加一
{
     
    if(node[nd].left==node[nd].right) {node[nd].num++;return ;}
    
    int mid=(node[nd].left+node[nd].right)/2;
    if(pos<=mid)  update(pos,nd*2);
    else update(pos,nd*2+1);
    node[nd].num=node[nd*2].num+node[nd*2+1].num;
}
int main()
{
    int n,i,j;
    while(scanf("%d",&n)!=EOF)
    {
          for(i=0;i<n;i++)
              scanf("%d",&a[i]);
          build(0,n-1,1);
          int sum=0;
          for(i=0;i<n;i++)
          {
     
              sum+=query(a[i]+1,n-1,1);//查询在线段树中大于a[i]的数据出现的次数
              update(a[i],1);//将a[i]插入到线段数中去
          }
          int ans=99999999;
          if(ans>sum)  ans=sum;
           for(i=0;i<n;i++)
           {
               sum=sum-a[i]+n-1-a[i];
               if(ans>sum) ans=sum;
           }
 
               printf("%d\n",ans);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Cworld2017/article/details/81606188