HDU 1394 线段树统计逆序对 解题报告

来源:互联网 发布:c盘里面的windows.old 编辑:程序博客网 时间:2024/06/05 12:06

Minimum Inversion Number

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的排列,那么如果把第一个数放到最后,对于这个数列,逆序数是减少a[i],而增加n-1-a[i]的.当然,你也可以是统计小于这个数的有多少个,然后再用已经插入树中i个元素减去小于这个数的个数,得出的结果也是在一样的

代码如下:

#include<cstdio>#include<cstring>#include<algorithm> using namespace std;#define N 5010struct Node{    int l,r;    int num;}tree[N<<2];void build(int i,int l,int r){    int mid=(l+r)>>1;    tree[i].l=l;tree[i].r=r;    tree[i].num=0;    if(l==r) return;    build(i<<1,l,mid);    build(i<<1|1,mid+1,r);}void updata(int i,int k){    if(tree[i].l==k&&tree[i].r==k)    {        tree[i].num=1;        return;    }    int mid=(tree[i].l+tree[i].r)>>1;    if(k<=mid) updata(i<<1,k);    else updata(i<<1|1,k);    tree[i].num=tree[i*2].num+tree[i*2+1].num;}int getsum(int i,int k,int n){    if(k<=tree[i].l&&tree[i].r<=n) return tree[i].num;    else    {        int mid=(tree[i].l+tree[i].r)>>1;        int sum1=0,sum2=0;        if(k<=mid) sum1=getsum(i<<1,k,n);        if(n>mid) sum2=getsum(i<<1|1,k,n);        return sum1+sum2;    }}int main(){    int n;    while(scanf("%d",&n)!=EOF)    {        int a[N];        build(1,0,n-1);        int i;        int ans=0;        for(i=0;i<n;i++)        {            scanf("%d",&a[i]);            ans+=getsum(1,a[i]+1,n-1);            updata(1,a[i]);        }        int minx=ans;        for(i=0;i<n;i++)        {            ans=ans+n-2*a[i]-1;                      if(ans<minx) minx=ans;        }        printf("%d\n",minx);    }    return 0;}