hdu1394Minimum Inversion Number(线段树,求出逆序数)

来源:互联网 发布:python list 遍历 编辑:程序博客网 时间:2024/05/18 19:40
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
101 3 6 9 0 8 5 7 4 2

Sample Output
16
题目意思是:求出循环n次中最小的逆序数。
#include<stdio.h>#define N 5000struct nod{    int fmax,fmin,rmax,rmin,w;//分别代表序列的前方比w大的个数,小的个数,后方比w大的个数,小的个数}node[N+5];int tree[4*N],fmax,fmin;void biulde(int l,int r,int k){    int m=(l+r)/2;    tree[k]=0;    if(l==r) return ;    biulde(l,m,k*2); biulde(m+1,r,k*2+1);}void updata(int l,int r,int k,int w){    int m=(l+r)/2;    tree[k]++;    if(l==r)        return ;    if(w<=m)//往左走    {        fmax+=tree[k*2+1];//记录比w大的个数        updata(l,m,k*2,w);    }    if(w>m)//往右走    {        fmin+=tree[k*2];//记录比w小的个数        updata(m+1,r,k*2+1,w);    }}int main(){    int n,minI,I;    while(scanf("%d",&n)>0)    {        biulde(1,n,1); I=0;        for(int i=1;i<=n;i++)        {            scanf("%d",&node[i].w); node[i].w++;            fmax=0; fmin=0;            updata(1,n,1,node[i].w);            node[i].fmax=fmax;//前面输入的比w大的个数            node[i].fmin=fmin;//前面输入的比w小的个数            node[i].rmax=(n-node[i].w)-fmax;//根据前面的可推出后面比w大的个数            node[i].rmin=(node[i].w-1)-fmin;//根据前面的可推出后面比w小的个数            I+=fmax;//记录输入序列的总逆序数        }        minI=I;//记录n个(循环)序列的最小的总逆序数        for(int i=1;i<n;i++)//把第i个数放到序列的最后        {            I=I-node[i].rmin;//移动后,对后方小于w(i)的逆序数的影响            I=I-node[i].fmin;//移动后,对己经循环的前方数(小于w(i))的逆序数的影响            I=I+node[i].fmax;//移动后,对本身(小于己经循环的前方数的逆序数)的影响            I=I+node[i].rmax;//移动后,对本身(小于还没循环数的逆序数)的影响            if(I<minI) minI=I;        }       printf("%d\n",minI);    }}