HDU 1394 线段树

来源:互联网 发布:sql注入 编辑:程序博客网 时间:2024/06/08 11:46

Minimum Inversion Number

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 17171    Accepted Submission(s): 10441


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

http://acm.hdu.edu.cn/showproblem.php?pid=1394 //题目链接

http://blog.csdn.net/weizhuwyzc000/article/details/50407450 //友情链接

先百科一下逆序数的概念: 在一个排列中,如果一对数的前后位置与大小顺序相反,即前面的数大于后面的数,那么它们就称为一个 逆序 。一个排列中逆序的总数就称为这个排列的 逆序数 。逆序数为 偶数 的排列称为 偶排列 ;逆序数为奇数的排列称为 奇排列 。如2431中,21,43,41,31是逆序,逆序数是4,为偶排列。

逆序数计算方法是:在逐个元素读取原始数列时,每次读取都要查询当前已读取元素中大于当前元素的个数,加到sum里,最后得到的sum即为原始数列的逆序数。

接下来找数列平移后得到的最小逆序数,假设当前序列逆序数是sum,那么将a[0]移到尾部后逆序数的改变是之前比a[0]大的数全部与尾部a[0]组合成逆序数,假设数量为x,则x=n-1-a[0],而之前比a[0]小的数(也就是之前能和a[0]组合为逆序数的元素)不再与a[0]组合成逆序数,假设数量为y,则y=n-x-1,这样,新序列的逆序数就是sum+x-y=sum-2*a[0]+n-1;

接下来说明下线段树的作用,线段区间表示当前已读取的元素个数,比如[m,n]表示在数字m到n之间有多少个数已经读入,build时所有树节点全部为0就是因为尚未读数,update函数是将新读入的数字更新到线段树里,点更新,query函数是查询当前数字区间已存在的数字个数。

暴力 也可以过 就是找到这个规律就行

#include<stdio.h>#include<algorithm>using namespace std;int str[5005*4];void build(int l,int r,int rt){    str[rt]=0;    if(l==r)    return ;    build(l,(l+r)/2,rt*2);    build((l+r)/2+1,r,rt*2+1);}int query(int L,int R,int l,int r,int rt){   if(L<=l&&R>=r)     return  str[rt];      int ret=0;   if(L<=(l+r)/2) ret+=query(L,R,l,(l+r)/2,rt*2);   if(R>(l+r)/2)  ret+=query(L,R,(l+r)/2+1,r,rt*2+1);    return ret;}void update(int p,int l,int r,int rt){     if(l==r)      {      str[rt]++;return ;      }  if(p<=(l+r)/2)  update(p,l,(l+r)/2,rt*2);  else  update(p,(l+r)/2+1,r,rt*2+1);  str[rt]=str[rt*2]+str[rt*2+1];}int main(){    int n;    int a[6000];    while(scanf("%d",&n)!=EOF)    {        build(1,n,1);        int sum=0;        for(int i=1; i<=n; i++)        {            scanf("%d",&a[i]);            a[i]++;            sum+=query(a[i],n,1,n,1);            update(a[i],1,n,1);        }        int  ans=sum;        for(int i=1; i<=n; i++)        {            sum=sum-(a[i]-1)+(n-a[i]);            ans=min(ans,sum);        }        printf("%d\n",ans);    }    return 0;}



0 0