【AcWing 1252. 搭配购买】并查集 + 01背包

题目链接

题意:

Joe觉得云朵很美,决定去山上的商店买一些云朵。

商店里有 n 朵云,云朵被编号为 1,2,…,n,并且每朵云都有一个价值。

但是商店老板跟他说,一些云朵要搭配来买才好,所以买一朵云则与这朵云有搭配的云都要买。

但是Joe的钱有限,所以他希望买的价值越多越好。

分析:

很明显的并查集,然后把每个集合当成一个个体进行01背包即可,下面请看代码:

#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N = 10010;
int pa[N],c[N],w[N];
int find(int x){
    if(x != pa[x]) pa[x] = find(pa[x]);
    return pa[x];
}
vector<int> alls;
int f[N];
signed main(){
    int n,m,q;
    scanf("%lld%lld%lld",&n,&m,&q);
    for(int i=1;i<=n;i++) pa[i] = i;
    for(int i=1;i<=n;i++) scanf("%lld%lld",&c[i],&w[i]);
    for(int i=1;i<=m;i++){
        int x,y;
        scanf("%lld%lld",&x,&y);
        int fx = find(x),fy = find(y);
        if(fx == fy) continue;
        pa[fx] = fy;
        c[fy] += c[fx];
        w[fy] += w[fx];
    }
    for(int i=1;i<=n;i++){
        alls.push_back(find(i));
    }
    sort(alls.begin(),alls.end());
    alls.erase(unique(alls.begin(),alls.end()),alls.end());
    for(int i=0;i<alls.size();i++){
        int t = alls[i];
        for(int j=q;j>=c[t];j--){
            f[j] = max(f[j],f[j-c[t]]+w[t]);
        }
    }
    cout<<f[q]<<endl;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

宇智波一打七~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值