Business (disjoint-set + 01 backpack)

https://ac.nowcoder.com/acm/problem/14545

 

#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e4 + 5;
int t,n,m,a[maxn],b[maxn],c;
int fa[maxn],dp[505];
void Init(){
    for(int i = 1; i <= n; i++)
        fa[i] = i;
}
int find(int x){
    if(x == fa[x])
        return x;
    return fa[x] = find(fa[x]);
}
void merge(int x,int y){
   fa[find(x)] = find(y);
}
int main(){
    //freopen("in","r",stdin);
    ios::sync_with_stdio(0);
    cin >> t;
    while(t--){
        cin >> n >> m >> c;
        Init();
        memset(dp,0, sizeof(dp));
        for(int i = 2; i <= n; i++)
            cin >> a[i] >> b[i];
        for(int i = 1; i <= m; i++){
            int x,y;
            cin >> x >> y;
            if(find(x) != find(y))
                merge(x,y);
        }
        for(int i = 2; i <= n; i++){
            if(find(i) == find(1)){
                for(int j = c; j >= a[i];j--){
                    dp[j] = max(dp[j],dp[j - a[i]] + b[i]);
                }
            }
        }
        cout << dp[c] << endl;
    }
    return 0;
}
View Code

 

And check collection and relationships

01 backpack found max

Guess you like

Origin www.cnblogs.com/xcfxcf/p/12462817.html