HDU 6318 Swaps and Inversions(逆序对)

本文介绍了一种算法问题——给定序列通过交换相邻元素减少逆序对的最小代价计算方法。利用离散化和树状数组求解逆序对数量,并通过比较操作代价确定最优策略。

题目链接:Swaps and Inversions

题意

对于一个长度为 n n 的序列,如果序列中存在一个逆序对,则需要花费 x 的代价,为了减少代价,可以先将任意个相邻的数字进行交换,每次交换需要花费 y y 的代价,问总的最小代价为多少?

输入

10 组输入,每组输入的第一行为三个整数 n,x,y (1n,x,y105) n , x , y   ( 1 ≤ n , x , y ≤ 10 5 ) ,第二行为 n n 个整数 a1,a2,,an (109ai109)

输出

输出最小代价。

样例

输入
3 233 666
1 2 3
3 1 666
3 2 1
输出
0
3
题解

由于每次代价为 y y 的操作最多能减少一个逆序对,所以代价为 y 的操作次数与最终序列中剩下的逆序对的数量和,等于初始序列的逆序对数,因此答案就是总的逆序对数乘上 min(x,y) min ( x , y ) 。对整个序列离散化然后用树状数组求逆序对。

过题代码

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cstring>
#include <string>
#include <vector>
#include <list>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <bitset>
#include <algorithm>
using namespace std;

#define LL long long
const int maxn = 100000 + 100;
struct Node {
    int num, Index;
};

bool operator<(const Node &a, const Node &b) {
    return a.num < b.num;
}

int n, cnt;
Node node[maxn];
LL x, y, ans;
int num[maxn], sum[maxn];

int lowbit(int x) {
    return (x & (-x));
}

void update(int Index, LL x) {
    while(Index <= n) {
        sum[Index] += x;
        Index += lowbit(Index);
    }
}

int query(int Index) {
    LL ret = 0;
    while(Index > 0) {
        ret += sum[Index];
        Index -= lowbit(Index);
    }
    return ret;
}

int query(int l, int r) {
    return query(r) - query(l - 1);
}


int main() {
    #ifdef Dmaxiya
    freopen("test.txt", "r", stdin);
    #endif // Dmaxiya

    while(scanf("%d%I64d%I64d", &n, &x, &y) != EOF) {
        ans = 0;
        for(int i = 1; i <= n; ++i) {
            scanf("%d", &num[i]);
            node[i].num = num[i];
            node[i].Index = i;
            sum[i] = 0;
        }
        sort(node + 1, node + n + 1);
        cnt = 1;
        num[node[1].Index] = cnt;
        for(int i = 2; i <= n; ++i) {
            if(node[i].num != node[i - 1].num) {
                ++cnt;
            }
            num[node[i].Index] = cnt;
        }
        for(int i = 1; i <= n; ++i) {
            ans += query(num[i] + 1, n);
            update(num[i], 1);
        }
        printf("%I64d\n", min(x, y) * ans);
    }

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值