码迷,mamicode.com
首页 > 其他好文 > 详细

逆序数&&线段树

时间:2018-05-20 18:10:54      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:namespace   get   contains   oid   rom   tput   seq   线段   upd   

                  Minimum Inversion Number    hdu 1394

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. 

InputThe 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. 
OutputFor 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

 

每次可以将第一个数放在最后构成一个新的序列,然后求逆序数最少的序列。

1 3 6 9 0 8 5 7 4 2  变成 3 6 9 0 8 5 7 4 2 1  我们发现逆序数减少了3个(0,1,2)但增加了10-3-1=6个(6,9,8,5,7,4)也就是 n-a[i]-1个

我们使用线段树的思想,每次我们插入判断 a[i]+1~n 也就是比a[i]大的数是否出现过,出现过那个就是一个逆序对。

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<ctime>
#include<cmath>
#define maxn 5100
#define ll long long int
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
using namespace std;
int a[maxn],sum[maxn<<2];
void pushup(int rt)
{
    sum[rt]=sum[rt<<1]+sum[rt<<1|1];
}
void build(int l,int r,int rt)
{
    sum[rt]=0;
    if(l==r)
        return ;
    int m=(l+r)>>1;
    build(lson);
    build(rson);
}
void updata(int L,int l,int r,int rt)
{
    if(l==r)
    {
        sum[rt]++;
        return ;
    }
    int m=(l+r)>>1;
    if(L<=m)
        updata(L,lson);
    else updata(L,rson);
    pushup(rt);
}
int query(int L,int R,int l,int r,int rt)
{
    if(L<=l&&R>=r)
        return sum[rt];
    int m=(l+r)>>1;
    int cnt=0;
    if(L<=m)
        cnt+=query(L,R,lson);
    if(R>m)
        cnt+=query(L,R,rson);
    return cnt;
}
int main()
{
    int n;
    while(~scanf("%d",&n))
    {
        int ans=0;
        build(1,n,1);
        for(int i=1; i<=n; i++)
        {
            scanf("%d",&a[i]);
            ans+=query(a[i]+1,n,1,n,1);
            updata(a[i]+1,1,n,1);
        }
        int Min=ans;
        for(int i=1; i<=n; i++)
        {
            ans+=n-a[i]*2-1;
            Min=min(ans,Min);
        }
        printf("%d\n",Min);
    }
}

使用树状数组也能解出来。溜了~~~

 

 

PS:摸鱼怪的博客分享,欢迎感谢各路大牛的指点~

逆序数&&线段树

标签:namespace   get   contains   oid   rom   tput   seq   线段   upd   

原文地址:https://www.cnblogs.com/MengX/p/9063848.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!