HDU 6318 Swaps and Inversions 逆序对

题目链接:Swaps and Inversions

题意

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

输入

10 组输入,每组输入的第一行为三个整数 n , x , y   ( 1 n , x , y 10 5 ) ,第二行为 n 个整数 a 1 , a 2 , , a n   ( 10 9 a i 10 9 )

输出

输出最小代价。

样例

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

题解

由于每次代价为 y 的操作最多能减少一个逆序对,所以代价为 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;
}

猜你喜欢

转载自blog.csdn.net/CSDNjiangshan/article/details/81352248
今日推荐