Luo Gu P1455 solution to a problem with a purchase disjoint-set +01 backpack

Topic links: https://www.luogu.com.cn/problem/P1455

Problem-solving ideas:
This question is the first with disjoint-set to belong to the same set of items fit together, and then do 01 backpack for each set of articles.

Codes are as follows:

#include <bits/stdc++.h>
using namespace std;
const int maxn = 10010;
int f[maxn], c[maxn], d[maxn], n, m, V, dp[maxn];
// 01背包部分
void pack01(int c, int v) {
    for (int i = V; i >= c; i --)
        dp[i] = max(dp[i], dp[i-c]+v);
}
// 并查集部分
void init() {
    for (int i = 1; i <= n; i ++)
        f[i] = i;
}
int Find(int x) {
    if (x == f[x]) return x;
    return f[x] = Find(f[x]);
}
void Union(int x, int y) {
    int a = Find(x), b = Find(y);
    if (a == b) return;
    f[a] = f[b] = f[x] = f[y] = a;
    c[a] += c[b];
    d[a] += d[b];
}
int main() {
    cin >> n >> m >> V;
    init();
    for (int i = 1; i <= n; i ++) cin >> c[i] >> d[i];
    while (m --) {
        int u, v;
        cin >> u >> v;
        Union(u, v);
    }
    for (int i = 1; i <= n; i ++) if (Find(i)==i) pack01(c[i], d[i]);
    cout << dp[V] << endl;
    return 0;
}

Guess you like

Origin www.cnblogs.com/quanjun/p/12337911.html