洛谷 #1892. 团伙

版权声明:转载请注明出处 https://blog.csdn.net/qq_41593522/article/details/84402933

题意

给出m对关系 (朋友 or 敌人),朋友的朋友 -> 朋友,敌人的敌人 -> 朋友

问集合个数

题解

又复习了一下正反集

朋友: 合并x,y的正集

敌人: 合并x的反集和y的正集,y的反集的x的正集

y的反集(敌人)-> x的敌人y的敌人 -> x的朋友

调试记录

#include <cstdio>
#define maxn 1005

using namespace std;

int f[maxn * 2], n, m;

int getf(int x){
	return (x == f[x]) ? x : f[x] = getf(f[x]);
}

int main(){
	scanf("%d%d", &n, &m);
	
	for (int i = 1; i <= 2 * n; i++) f[i] = i;
	
	int u, v; char opt[2];
	while (m--){
		scanf("%s%d%d", &opt, &u, &v);
		
		if (opt[0] == 'F') f[getf(u)] = getf(v);
		if (opt[0] == 'E'){
			f[getf(u + n)] = getf(v);
			f[getf(v + n)] = getf(u);
		}
	}
	
	int ans = 0;
	for (int i = 1; i <= n; i++)
		if (getf(i) == i) ans++;
	printf("%d\n", ans);
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41593522/article/details/84402933
今日推荐