hdu 1394 Minimum Inversion Number

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

题意:

给定一组序列a1, a2, ..., an

a1, a2, ..., an-1, an 
a2, a3, ..., an, a1
a3, a4, ..., an, a1, a2
...
an, a1, a2, ..., an-1

中找出最小的逆序。

思路:

找出a1, a2, ..., an的逆序,然后再逐一枚举,注意线段树是1~n.

#include <iostream>
#include <cstdio>
#include <string.h>

#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1

using namespace std;
const int maxn = 5005;
int a[maxn];
int tree[maxn<<2];

void PushUp(int rt){
    tree[rt] = tree[rt<<1]+tree[rt<<1|1];
}

void build(int l, int r, int rt){
    if (l == r){
        tree[rt] = 0;
        return;
    }
    int  m = (l + r) >> 1;
    build (lson);
    build (rson);
    PushUp(rt);
}

void update(int id ,int p, int l, int r, int rt){
    if (l == r){
        tree[rt] = p;
        return ;
    }
    int m = (l + r) >> 1;
    if (id <= m)
        update(id,p,lson);
    else
        update(id,p,rson);
    PushUp(rt);
}
int query(int L,int R,int l,int r,int rt){
    if(L <= l && r <= R){
        return tree[rt];
    }
    int m = (l + r)>>1;
    int ret = 0;
    if(L <= m)
        ret += query(L, R, lson);
    if(R > m)
        ret += query(L, R, rson);
    return ret;
}

int main(){
    int n;
    while(~scanf("%d",&n)){
        build(1,n,1);
        int res = 0;
        
        for(int i = 1;i <= n;i++){
            scanf("%d",a+i);
            update(a[i]+1, 1, 1, n, 1);
            res += query(a[i]+2, n, 1, n, 1);
        }
        //printf("%d\n",res);
        int ans = res;
        for(int i = 1;i <= n;i++){
            res += n - 2*a[i] - 1;
            //printf("%d\n",res);
            ans = min(ans,res);
        }
        printf("%d\n",ans);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值