AcWing 1252. 搭配购买
原题链接
简单
作者:
acw_weian
,
2020-09-06 21:56:27
,
所有人可见
,
阅读 504
- 并查集, 将捆绑销售的物品合并成一个物品
- 只枚举父节点指向自己本身的物品, dp 01背包问题
import java.io.*;
class Main{
static BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
static int N = 10010, V, n, m;
static int[] dp = new int[N], v = new int[N], w = new int[N];
static int[] f = new int[N];
public static void main(String[] args) throws Exception{
String[] ss = read.readLine().split(" ");
n = Integer.valueOf(ss[0]); m = Integer.valueOf(ss[1]);
V = Integer.valueOf(ss[2]);
for(int i = 1; i <= n; i++){
ss = read.readLine().split(" ");
v[i] = Integer.valueOf(ss[0]);
w[i] = Integer.valueOf(ss[1]);
}
for(int i = 1; i <= n; i++) f[i] = i;
for(int i = 1; i <= m; i++){
ss = read.readLine().split(" ");
int a = Integer.valueOf(ss[0]);
int b = Integer.valueOf(ss[1]);
int f1 = find(a), f2 = find(b);
if(f1 != f2){
f[f1] = f2;
v[f2] += v[f1];
w[f2] += w[f1];
}
}
for(int i = 1; i <= n; i++){
if(f[i] != i) continue;
for(int j = V; j >= v[i]; j--){
dp[j] = Math.max(dp[j], dp[j - v[i]] + w[i]);
}
}
System.out.println(dp[V]);
}
public static int find(int x){
if(f[x] != x) f[x] = find(f[x]);
return f[x];
}
}