2018.07.08 hdu1394 Minimum Inversion Number

Minimum Inversion Number
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
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
ZOJ Monthly, January 2003
Recommend
Ignatius.L | We have carefully selected several similar problems for you: 1166 1698 1540 1542 1255

看到题的第一眼还以为是动态逆序对,读完题后发现竟然是一道水题。

这道题想让我们求的是在不断改变元素的顺序之后所有逆序对的最小值。怎么做?首先我们知道在进行 n 次轮换之后数列又变回去了,所以我们只需用一种高效的方法统计出每次轮换后数列逆序对的个数就行了。

怎么统计?

显然第一次逆序对直接上树状数组(线段树)求 s o e a s y ,那么之后的轮换呢?用 n 次树状数组== g g ,因此可以想到这样轮换有特殊的性质。没错就是这样。我们考虑当前队首的元素,这个元素从队首移到队尾的操作可以拆成队首弹出,队尾插入的操作,设上一次的逆序对数为 s u m ,那么这个元素从队首弹出显然会使 s u m 减少 a 1 1 ,道理显然( a 1 之后有 a 1 1 个数比它小),同理,这个元素从队尾插入会使 s u m 变大 n a 1 (证明同理)。这样看来的话似乎一个循环比比大小就没了啊。

代码如下:

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#define N 5005
using namespace std;
int n,bit[N],a[N],sum,ans;
inline int read(){
    int ans=0;
    char ch=getchar();
    while(!isdigit(ch))ch=getchar();
    while(isdigit(ch))ans=(ans<<3)+(ans<<1)+ch-'0',ch=getchar();
    return ans;
}
inline int lowbit(int x){return x&-x;}
inline void update(int x,int v){for(int i=x;i<=n;i+=lowbit(i))bit[i]+=v;}
inline int query(int x){int ans=0;for(int i=x;i;i-=lowbit(i))ans+=bit[i];return ans;}
int main(){
    while(~scanf("%d",&n)){
        sum=ans=0;
        memset(a,0,sizeof(a));
        memset(bit,0,sizeof(bit));
        for(int i=1;i<=n;++i){
            a[i]=read()+1;
            sum+=query(n)-query(a[i]);
            update(a[i],1);
        }
        ans=sum;
        for(int i=1;i<=n;++i)ans=min(ans,sum=sum-a[i]+1+n-a[i]);
        printf("%d\n",ans);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/dreaming__ldx/article/details/80957223