【题解】CF1209D:Cow and Snacks

原题传送门
对于同一只动物喜欢的两种点心,用并查集连边
建好图后,对于一个点数>1的连通块,假设大小为 x x ,用最优策略必定能满足 x 1 x-1 只动物,因为第一个来的必须取走两个,剩下的可以使得他们都只取走一个
再转换一下思路,对于一个动物,如果他喜欢的两种点心尚未在同一个连通块里,那么他在最优策略下是一定能被满足的,那就答案+1,并且并查集合并
然后我们求的是不能被满足的有多少

Code:

#include <bits/stdc++.h>
#define maxn 200010
using namespace std;
int n, m, f[maxn], ans;

inline int read(){
	int s = 0, w = 1;
	char c = getchar();
	for (; !isdigit(c); c = getchar()) if (c == '-') w = -1;
	for (; isdigit(c); c = getchar()) s = (s << 1) + (s << 3) + (c ^ 48);
	return s * w;
}

int getfa(int k){ return f[k] == k? k : f[k] = getfa(f[k]); }

int main(){
	n = read(), m = read();
	for (int i = 1; i <= n; ++i) f[i] = i;
	for (int i = 1; i <= m; ++i){
		int x = read(), y = read(), s1 = getfa(x), s2 = getfa(y);
		if (s1 != s2) f[s1] = s2, ++ans;
	}
	printf("%d\n", m - ans);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/ModestCoder_/article/details/108186561
今日推荐