codefores741B Arpa's weak amphitheater and Mehrdad's valuable Hoses(并查集+背包)

题意:

给出一些女孩的体重和美貌程度,这些女孩是按照组在一起的,要么选一整个组,要么只能选组里的一个,最后求总重量为W的女孩最大美貌程度

要求:

这一看就是并查集+背包,主要是这个选择的问题,用背包时按组数遍历,每次状态转移一整个组或遍历整个组转移其中一个女孩,这里面的状态转移一开始没怎么搞清楚。

#include<iostream>
#include<string>
#include<algorithm>
#include<functional>
#include<cstring>
#include<vector>
using namespace std;
const int N = 1005;
int n, m, weight;
int fa[N], w[N],b[N];
int dp[N];
vector<int> group[N];

int find(int x)
{
	return fa[x] == x ?x: fa[x] = find(fa[x]);
}

int main()
{
	cin >> n >> m >> weight;
	for (int i = 1; i <= n; i++)
		scanf("%d", &w[i]);
	for (int i = 1; i <= n; i++)
		scanf("%d", &b[i]);
	for (int i = 1; i <= n; i++) fa[i] = i;
	for (int i = 1; i <= m; i++)
	{
		int u, v;
		cin >> u >> v;
		int x = find(u);
		int y = find(v);
		if (x != y)
		{
			fa[x] = y;
		}
	}
	for (int i = 1; i <= n; i++)
	{
		int x = find(i);
		group[x].push_back(i);
	}
	memset(dp, 0, sizeof(dp));
	for (int i = 1; i <= n; i++)
	{
		int x = find(i);
		if (i != x)
			continue;
		for (int j = weight; j >= 0; j--)
		{
			int sumb = 0, sumw = 0;
			for (int k = 0; k < group[x].size(); k++)
			{
				sumb += b[group[x][k]];
				sumw += w[group[x][k]];
				if (j >= w[group[x][k]])
					dp[j] = max(dp[j], dp[j - w[group[x][k]]]+ b[group[x][k]]);
			}
			if (j >= sumw)
				dp[j] = max(dp[j], dp[j - sumw]+sumb);
		}
	}
	printf("%d\n", dp[weight]);
	return 0;
}


posted @ 2016-12-10 12:05  seasonal  阅读(79)  评论(0编辑  收藏  举报