首页 > 代码库 > HDU Minimum Inversion Number

HDU Minimum Inversion Number

  经典的线段树求解逆序数问题。

  运用了一个逆序数的性质,如果一个数从首位换到尾位,这其逆序数将减少y[i],增加n-y[i]-1。

  举个例子说明,如果一个排列3 1 2 0 4本来三前面应该有三个数比他小的,但是现在3在首位,则说明3产生的逆序数有3个,而将3换到尾位后,就说明比3大的都在3前面了,所以此时3的逆序数有n-y[i]-1(5-3-1 = 1).

 线段树的话,先建立一个空树,每次不断的查询插入。就是一开始先查询树中有多少个数比当前要插入的值大,就说明改数拥有多少个逆序数。查询后,在把改数插入,不断重复。就可以得出答案。


#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
using namespace std;

#define L(x) (x<<1)
#define R(x) (x<<1|1)
#define lson lft,mid,rt<<1
#define rson mid+1,rht,rt<<1|1
#define MID(a,b) (a+((b-a)>>1))

const int MAXN = 5000+10;
struct Node{
   int lft,rht,val;
   int mid(){return MID(lft,rht);}
};
Node tree[4*MAXN];
int y[MAXN],n;
class Segtree{
public:
    void Build(int lft,int rht,int rt){
        tree[rt].lft = lft; tree[rt].rht = rht;
        tree[rt].val = 0;
        if(lft != rht){
            int mid = tree[rt].mid();
            Build(lson);
            Build(rson);
        }
    }
    void Update(int pos,int rt){
        int lft = tree[rt].lft,rht = tree[rt].rht;
        if(lft == rht)tree[rt].val++;
        else{
            int mid = tree[rt].mid();
            if(pos <= mid)Update(pos,L(rt));
            if(pos > mid)Update(pos,R(rt));
            tree[rt].val = tree[L(rt)].val + tree[R(rt)].val;
        }
    }
    int Query(int st,int ed,int rt){
         int lft = tree[rt].lft,rht = tree[rt].rht;
         if(st <= lft&&rht <= ed)return tree[rt].val;
         else{
            int mid = tree[rt].mid();
            int sum1 = 0,sum2 = 0;
            if(st <= mid) sum1 += Query(st,ed,L(rt));
            if(ed > mid) sum2 += Query(st,ed,R(rt));
            return sum1 + sum2;
         }
    }
};
int main()
{
    while(~scanf("%d",&n)){
        Segtree seg;
        seg.Build(0,n-1,1);
        int sum = 0;
        for(int i = 0;i < n;++i){
            scanf("%d",&y[i]);
            sum += seg.Query(y[i],n-1,1);
            seg.Update(y[i],1);
        }
        int ret = sum;
        for(int i = 0;i < n;++i){
            sum += (n-y[i]-1) - y[i];
            ret = min(ret,sum);
        }
        printf("%d\n",ret);
    }
    return 0;
}