CF741B Arpa's weak amphitheater and Mehrdad's valuable Hoses

洛谷题址
在这里插入图片描述
在这里插入图片描述
看完这道题,我们看见后面句对于一个朋友圈,要么选其中一个,要么全选,就很容易想到是分组背包,那么接下来考虑的就是
怎么转化成分组背包的形式

显然我们用并查集可以维护出每个朋友圈,那么对于每个朋友圈我们开一个vector维护朋友圈中的人,同时把所有人也当做一个人,加入到朋友圈中,然后在圈内做01背包就行了,注意的是,如果一个人没有朋友,那么他的朋友圈就不需要再增加一个所有人,不然的话那个人会出现两次

还有就是因为要向数组中增加一个所有人,所以数组需要开的比数据更大一点
C o d e Code Code

#include<bits/stdc++.h>

#define N 5001
#define ll long long
 
using namespace std;

inline void read(ll &s){
	s = 0; ll w = 1; char ch = getchar();
	while(ch < '0' || ch > '9'){if(ch == '-') w = -1, ch = getchar();}
	while(ch >= '0' && ch <= '9'){s = s * 10 + ch - '0'; ch = getchar();}
	s *= w; return ;
}
struct node{
	int x, y;
}e[N];

ll f[N], fa[N], a[N], b[N];
ll n, m, w, p;
vector<ll> group[N];

inline ll get(ll x){
	return fa[x] == x ? x : fa[x] = get(fa[x]);
}

int main()
{
	read(n), read(m), read(w);
	p = n;
	
	for(ll i = 1; i <= n; ++i) fa[i] = i, read(a[i]);
	
	for(ll i = 1; i <= n; ++i) read(b[i]);
	
	for(ll i = 1; i <= m; ++i){
		ll x, y;
		read(x), read(y);
		x = get(x), y = get(y);
		if(x != y) fa[y] = x;
	}
	
	for(ll i = 1; i <= n; ++i) group[get(i)].push_back(i);
	
	for(ll i = 1; i <= n; ++i){
		if(group[i].size() <= 1) continue;
		group[i].push_back(++p);
		for(ll j = 0; j < group[i].size() - 1; ++j)
			a[p] += a[group[i][j]], b[p] += b[group[i][j]];
	}
	
	for(ll k = 1; k <= n; ++k){
		if(!group[k].size()) continue;
		
		for(ll j = w; j >= 0; --j)
			for(ll i = 0; i < group[k].size(); ++i){
				ll x = group[k][i];
				if(j >= a[x]) f[j] = max(f[j], f[j - a[x]] + b[x]);
			}
	}
	
	printf("%d\n", f[w]);
	
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

BIGBIGPPT

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

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

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

打赏作者

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

抵扣说明:

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

余额充值