AcWing 1252. With the purchase (disjoint-set, 01 backpacks)

Topic links: Click here

Here Insert Picture Description
Here Insert Picture Description

Bind the volume and value of each item to the root, can be seen as the root of all the 01 knapsack problem

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>

using namespace std;
const int N = 10010;

int n, m, vol;
int f[N];
int v[N], w[N];
int dp[N];

int find(int x)
{
    if(f[x] != x)   f[x] = find(f[x]);
    return f[x];
}

int main()
{
    scanf("%d%d%d", &n, &m, &vol);
    
    for(int i = 1; i <= n; ++i) f[i] = i;
    
    for(int i = 1; i <= n; ++i) scanf("%d%d", &v[i], &w[i]);
    
    for(int i = 1; i <= m; ++i)
    {
        int a, b;
        scanf("%d%d", &a, &b);
        int fa = find(a), fb = find(b);
        if(fa != fb)
        {
            v[fb] += v[fa];
            w[fb] += w[fa];
            f[fa] = fb;
        }
    }
    
    for(int i = 1; i <= n; ++i)
    {
        if(f[i] == i)
        {
            for(int j = vol; j >= v[i]; j--)
            {
                dp[j] = max(dp[j], dp[j-v[i]] + w[i]);
                
            }
        }
    }
    
    printf("%d\n", dp[vol]);
    
    return 0;
}
Published 844 original articles · won praise 135 · Views 150,000 +

Guess you like

Origin blog.csdn.net/qq_42815188/article/details/105147371