CodeForces 95E Lucky Country (并查集+多重背包优化)

题意:n个点m条边,构成多个连通块,增加最少的边,使得至少有一个连通块的点个数只包含4和7。

题解:并查集+多重背包优化
先用并查集求出每个连通块的点的数量,增加边数,其实就是将几个连通块组合,看是否满足要求。我们用多重背包。
对于背包里的物品,数量就是相同点数的连通块数量,价值就是单个连通块包含的点数。求出 d p [ i ] dp[i] dp[i]表示 i i i个连通块具有的价值,即点数总和。

#define _CRT_SECURE_NO_WARNINGS
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define ll long long
using namespace std;
const int Max = 1e5 + 5;
int Parent[Max], Rank[Max], rep[Max], cnt;
int Find(int x) {
	return Parent[x] == x ? x : Parent[x] = Find(Parent[x]);
}
void Union(int x, int y) {
	int u, v, root;
	u = Find(x);
	v = Find(y);
	if (u == v) {
		return;
	}
	if (Rank[u] <= Rank[v]) {
		rep[v] += rep[u];
		root = Parent[u] = v;
		if (Rank[u] == Rank[v])
			Rank[v]++;
	}
	else {
		rep[u] += rep[v];
		root = Parent[v] = u;
	}
	//return root;
}
bool check(int x) {
	while (x) {
		if (x % 10 != 4 && x % 10 != 7) return 0;
		x /= 10;
	}
	return 1;
}
int n, m, x, y, a[Max], dp[Max];
vector<int> v, num;
int main() {
	scanf("%d%d", &n, &m);
	for (int i = 1; i <= n; i++) Parent[i] = i, rep[i] = 1;
	for (int i = 1; i <= m; i++) {
		scanf("%d%d", &x, &y);
		Union(x, y);
	}
	for (int i = 1; i <= n; i++) {
		if (Parent[i] == i) a[rep[i]]++;
	}
	for (int i = 1; i <= n; i++) {
		if (a[i]) {
			v.push_back(i);
			num.push_back(a[i]);
		}
	}
	memset(dp, 0x3f, sizeof(dp));
	dp[0] = 0;
	int nm = v.size();
	for (int i = 0; i < nm; i++) {
		if (v[i] * num[i] >= n) {
			for (int j = v[i]; j <= n; j++) {
				dp[j] = min(dp[j], dp[j - v[i]] + 1);
			}
			continue;
		}
		int x = num[i];
		for (int k = 1; k <= x; k *= 2) {
			for (int j = n; j >= v[i] * k; j--) {
				dp[j] = min(dp[j], dp[j - v[i] * k] + k);
			}
			x -= k;
		}
		if (x) {
			for (int j = n; j >= v[i] * x; j--) {
				dp[j] = min(dp[j], dp[j - v[i] * x] + x);
			}
		}
	}
	int ans = 0x3f3f3f3f;
	for (int i = 1; i <= n; i++)
		if (check(i)) ans = min(ans, dp[i]);
	if (ans == 0x3f3f3f3f) printf("-1\n");
	else printf("%d\n", ans - 1);
	return 0;
}

你可能感兴趣的:(#,并查集,#,简单dp)