HDU 1294 Minimum Inversion Number 树状数组

来源:互联网 发布:centos 732位下载 编辑:程序博客网 时间:2024/04/30 03:03

Minimum Inversion Number

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

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

题意:给你一个0到n-1的排列,每次可以把第一个数移到最后一个数去,求生成的所有序列中,逆序对数最少的那个,输出最少的逆序对数。

分析:
初始的逆序对数显然可以用树状数组快速得到,然后考虑将第一个数移到最后一个去,逆序对数就会减少a[i]-1,(比它小的数当它移到后面去的时候就无法构成逆序对了),但又要增加n-a[i]个(比它大的数构成逆序对)我们从小到大枚举每个位置,选出最少的即可。

用树状数组求逆序对:用sum[n]-sum[a[i]] 即可求出有多少比它大的数在它之前加入,即这个数构成的逆序对数目。

#include<cstdio>#include<cstring>#include<algorithm>using namespace std;const int N = 10010;int n;int ans=0;int a[N],c[N];inline int Min(int a,int b){    return a<b?a:b;}int lowbit(int x){    return x&(-x);}void add(int x){    while(x<=n){        c[x]+=1;        x+=lowbit(x);    }}int query(int x){    int ans=0;    while(x){        ans+=c[x];        x-=lowbit(x);    }    return ans;}#define ms(x,y) memset(x,y,sizeof(x))void update(){    ms(c,0);ans=0;}int main(){    while(scanf("%d",&n)!=EOF){       update();       for(register int i=1;i<=n;i++){          scanf("%d",&a[i]);          a[i]++;          ans+=query(n)-query(a[i]);          add(a[i]);       }       int mn=ans;       for(register int i=1;i<=n;i++){          mn+=n-a[i]-(a[i]-1);          ans=Min(ans,mn);       }       printf("%d\n",ans);    }    return 0;}
原创粉丝点击