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

洛谷题址
CF741B Arpa's weak amphitheater and Mehrdad's valuable Hoses
CF741B Arpa's weak amphitheater and Mehrdad's valuable Hoses
看完这道题,我们看见后面句对于一个朋友圈,要么选其中一个,要么全选,就很容易想到是分组背包,那么接下来考虑的就是
怎么转化成分组背包的形式

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

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

#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;
}
上一篇:Coredns 添加自定义DNS解析记录


下一篇:centos7安装dns正向解析2