动规(21)-并查集基础题——搭配购买

Description 

Joe觉得云朵很美,决定去山上的商店买一些云朵。商店里有n朵云,云朵被编号为1,2,...,n,并且每朵云都有一个价值。但是商店老板跟他说,一些云朵要搭配来买才好,所以买一朵云则与这朵云有搭配的云都要买。但是Joe的钱有限,所以他希望买的价值越多越好。 

Input 

输入有多组数据,每组数据第1n(<=10000)m(>=5000)w(<=10000),表示n朵云,m个搭配,Joew的钱。 

2n+1行,每行cidi表示i朵云的价钱和价值。 

n+2n+1+m行,每行uivi表示买ui就必须买vi,同理,如果买vi就必须买ui 

Output 

对于每组数据,输出一行,表示可以获得的最大价值。 

Sample Input 

5 3 10 

3 10 

3 10 

3 10 

5 100 

10 1 

1 3 

3 2 

4 2 

Sample Output 

#include <cstdio>
#include <iostream>
using namespace std;
const int maxn = 10010;
int fa[maxn], w[maxn], c[maxn], f[maxn];
int n, m, cnt, C, u, v;
int find(int x)
{
    return x == fa[x] ? x : fa[x] = find(fa[x]);
}
int main()
{
    scanf("%d%d%d", &n, &m, &C);
    for (int i = 1; i <= n; i++)
        scanf("%d%d", &w[i], &c[i]), fa[i] = i;
    for (int i = 0; i < m; i++)
    {
        scanf("%d%d", &u, &v);
        int x = find(u), y = find(v);
        if (x != y)
        {
            fa[x] = y;
            w[y] += w[x];
            c[y] += c[x];
        }
    }
    for (int i = 1; i <= n; i++)
        if (fa[i] == i)
        {
            w[++cnt] = w[i];
            c[cnt] = c[i];
        }
    for (int i = 1; i <= cnt; i++)
        for (int j = C; j >= w[i]; j--)
            f[j] = max(f[j], f[j - w[i]] + c[i]);
    printf("%d\n", f[C]);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/hdq1745/article/details/126812638
今日推荐