HDU 1394 Minimum Inversion Number

Thinking: Actually this problem can be solved in a violent way, which is not recommended. Here we made use of segment tree. The basic idea is to save the frequency(actually 0 or 1 for every number) of numbers. Sum in structure tree means "up till now, how many numbers have appear in this interval in total".

First we will use segment tree to calculate the first Minimum inversion number. Based on this , the following Minimum inversion number should be "previous + N-num[i]-num[i]-1".

The reason is that if you move the first number to the bottom of this sequence, "num[i]" pairs will lose, and in the meanwhile, "N-1-num[i]" pairs will be made.


AC code:

#include<iostream>
using namespace std;
#define maxn 5222
#define MIN(a,b) ((a)<(b)?(a):(b))
struct tree{
    int l,r,Sum;
}node[maxn*2];

int sequence[maxn];
void build(int rt,int left,int right)
{
    node[rt].l = left;
    node[rt].r = right;
    if(left == right)
        return;
    int mid = (left +right) >> 1;
    build(rt << 1,left,mid);
    build(rt << 1|1,mid+1,right);
}
void fix(int rt,int val)
{
    if(node[rt].l > val ||node[rt].r < val) {
        return;
    }
    if(node[rt].l == node[rt].r)
   {
       node[rt].Sum++;
       return;
   }
    fix(rt << 1,val);
    fix(rt << 1|1,val);
    node[rt].Sum = node[rt<<1].Sum+node[rt<<1|1].Sum;
}
int query(int rt,int left,int right)
{
    if(left > right)
        return 0;
    if(node[rt].r < left)
        return 0;
    if(node[rt].l >= left && node[rt].r <= right)
        return node[rt].Sum;

    if(node[rt].r == node[rt].l)
        return node[rt].Sum;
    return query(rt << 1,left,right)+query(rt << 1|1,left,right);
}
int main()
{
    int N;
    while(scanf("%d",&N)!=EOF)
    {
        memset(node,0,sizeof(node));
        build(1,0,N-1);
        int s = 0;
        for(int i = 0;i < N;i++)
        {
            scanf("%d",&sequence[i]);
            fix(1,sequence[i]);
            s += query(1,sequence[i]+1,N-1);
        }
        int ans = s;
        for(int i= 0;i < N;i++)
        {
            s += N-sequence[i]-sequence[i]-1;
            ans = MIN(ans,s);
        }

    printf("%d\n",ans);
    }
    
return 0;

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值