hdu 1394 (线段树推荐模板)

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,然后任意输入n个0到n-1之间的数,不重复,比如:

5

4 1 3 0 2

然后在

4 1 3 0 2 ……对应逆序数7

1 3 0 2 4……对应逆序数7+5-2*4-1=3

3 0 2 4 1……对应逆序数3+5-2*1-1=5

0 2 4 1 3……对应逆序数5+5-2*3-1=3

2 4 1 3 0……对应逆序数3+5-2*0-1=7


找出所有情况中找逆序数最小的值3。


从第一种情况开始,上面已经给出了规律,不过找到规律后问题就转化为怎么求第一个数列的逆序数。

这题用线段树其实确实非常合适,因为刚好所有的数字就是刚好从0到n-1,逆序数则就为记录前面已经输入的数字之中比输入的该数字x[i]大的数字的个数,那么转化为从区间x[i]+1到n已经输入的数字的个数,那么这一问题已经完全转化为了线段树更新与查询的问题了,输入一个数之后就更新对应线段与节点(该节点与对应线段数量++),然后查询比x[i]大的线段的对应数值就是该数逆序数的个数。


#include <cstdio>
#include <cstring>
#include <cstdlib>
#include<iostream>
using namespace std;
int x[5005],node[5005*4];
void update(int pos, int l, int r,int id)
{
    if(l == r)
    node[pos]++;
    else
    {
    int mid = (l + r) >> 1;
    if(id <= mid) update(pos*2, l, mid,id);
    else update(pos*2+1, mid+1, r,id);
    node[pos] = node[pos*2] + node[pos*2+1];
    }
}

int query(int rs,int l,int r,int ll,int rr)
{
    if(ll <= l && r <= rr)
        return node[rs];
    int mid=(l+r)>>1,ans=0;
    if(mid>=ll)ans+=query(rs*2,l,mid,ll,rr);
    if(mid<rr)ans+=query(rs*2+1,mid+1,r,ll,rr);
    return ans;
}
int main()
{
        int n;
        while(cin>>n)
        {
            memset(node,0,sizeof(node));
            int sum=0;
            for(int i=1;i<=n;i++)
            {
                cin>>x[i];
                sum+=query(1,1,n,x[i]+1,n);
                update(1,1,n,x[i]);
            }
            int min0=sum;
            for(int i=1;i<=n;i++)
            {
               // cout<<sum<<endl;;
                 sum = sum + n - 2 * x[i] - 1;
                 if(sum<min0)min0=sum;
            }
            cout<<min0<<endl;
        }
    return 0;
}




posted @ 2015-06-03 22:01  martinue  阅读(113)  评论(0)    收藏  举报