Codeforces 1315D Recommendations(并查集 + 贪心)

题目链接:https://codeforces.ml/contest/1315/problem/D

题意:给你n个数,以及每个数+1的代价,问你让所有的数都不相同的最小代价。

思路:首先考虑最简单的思路,每次我们让相同的数花费最小的+1,答案加上所需要的代价,这样一直处理到最后一个肯定可以出结果,但时间复杂度太大,会TLE。所以我们可以考虑用并查集去维护每个值所能达到的最大的位置,然后我们用 代价 * (最大的位置 - 当前的值)就是当前位置对答案的贡献。考虑贪心的思想,我们要按照代价从大到小去对结构体进行排序。具体代码如下。

AC代码:

#include <set>
#include <map>
#include <queue>
#include <vector>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>

using namespace std;

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

const int maxn = 2e5 + 7;

struct node {
    LL val;
    LL time;
}a[maxn];

bool cmp(node aa,node bb) {
    if(aa.time == bb.time) {
        return aa.val < bb.val;
    } else {
        return aa.time > bb.time;
    }
}

map<LL,LL>mp;

LL Find(int x) {
    if(mp[x] == 0) return x;
    else return mp[x] = Find(mp[x]);
}

void Merge(LL x,LL y) {
    LL t1 = Find(x);
    LL t2 = Find(y);
    if(t1 != t2) {
        mp[t1] = t2;
    }
}

int main() {
    int n;
    while(~scanf("%d",&n)) {
        mp.clear();
        for(int i = 1 ; i <= n ; i++) {
            scanf("%lld",&a[i].val);
        }
        for(int i = 1 ; i <= n ; i++) {
            scanf("%lld",&a[i].time);
        }
        sort(a+1,a+n+1,cmp);
//        for(int i = 1 ; i <= n ; i++) {
//            cout << "i = " << i << " " << a[i].val << " " << a[i].time << endl;
//        }
        LL ans = 0;
        for(int i = 1 ; i <= n ; i++) {
            LL res = Find(a[i].val);
//            cout << "res = " << res << endl;
            Merge(res,res+1);
            ans += a[i].time * (res - a[i].val);
        }
        printf("%lld\n",ans);
    }
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值