HDU-1394 Minimum Inversion Number 线段树+逆序对

来源:互联网 发布:手机淘宝怎么发布宝贝 编辑:程序博客网 时间:2024/06/05 08:06

仍旧在练习线段树中。。这道题一开始没有完全理解搞了一上午,感到了自己的shabi。。
Minimum Inversion Number
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 15527 Accepted Submission(s): 9471
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

题目大意:
给出一个n,和0-n的一个数列,求这个数列的最小逆序对数,最小逆序对表示,给定数列每次都将第一个数放到最后一个位置,如此变化n次至变换回原状,在这n种不同的数列中,逆序对数的最小值即为所求(N<=5000)每组样例多组数据

明白题意后想到求逆序对的三种方法,第一种暴力法,第二种归并,第三种树状数组和线段树,由于在学习线段树于是果断练习用线段树编写此处线段树的作用是求出原数列的逆序对对于每次变换,我们发现,第一个数移到最后一位,只需要在上一步里求出的逆序对减去上一步第一位的数,并加上比上一步第一位要大的数即可

下面是代码:

#include <cstdio>#include <algorithm>using namespace std;#define maxn 5005int sum[maxn<<2];int a[maxn];void updata(int now){    sum[now]=sum[now<<1]+sum[now<<1|1];}void build(int l,int r,int now){    sum[now]=0;    if(l==r) return;    int mid=(l+r)>>1;    build(l,mid,now<<1);    build(mid+1,r,now<<1|1);}int query(int L,int R,int l,int r,int now){    if(L<=l && r<=R)        return sum[now];    int mid=(l+r)>>1;    int total=0;    if(L<=mid) total+=query(L,R,l,mid,now<<1);    if(R>mid) total+=query(L,R,mid+1,r,now<<1|1);    return total;}void point_change(int loc,int l,int r,int now){    if(l==r)    {        sum[now]++;        return;    }    int mid=(l+r)>>1;    if(loc<=mid)         point_change(loc,l,mid,now<<1);    else         point_change(loc,mid+1,r,now<<1|1);    updata(now);}int main(){    int n;    while(~scanf("%d",&n))    {        build(0,n-1,1);        int number=0;        for(int i=0;i<n;i++)        {            scanf("%d",&a[i]);            number+=query(a[i],n-1,0,n-1,1);            point_change(a[i],0,n-1,1);        }        int ans=number;        for(int i=0;i<n;i++)        {            number+=n-a[i]-a[i]-1;            ans=min(ans,number);        }        printf("%d\n",ans);    }    return 0;}
0 0