蓝桥杯 PREV-54 合根植物(并查集)

题目链接:

PREV-54 合根植物

思路:

并查集裸题

代码:

#include<bits/stdc++.h>

using namespace std;

const int maxn = 1000 * 1000;
int par[maxn], rk[maxn], tot;
void init_set(int n) { tot = n; for(int i = 1; i <= n; i++) par[i] = i; }
inline int find(int x) {
	if(x == par[x]) return x;
	return par[x] = find(par[x]);
}
inline void unite(int x, int y) {
	x = find(x), y = find(y);
	if(x == y) return;
	if(rk[y] > rk[x]) { par[x] = y; return; }
	par[y] = x;
	if(rk[x] == rk[y]) ++rk[x];	
}

int main() {
#ifdef MyTest
	freopen("Sakura.txt", "r", stdin);
#endif
	int m, n, k;
	scanf("%d %d %d", &m, &n, &k);
	init_set(m * n);
	while(k--) {
		int x, y;
		scanf("%d %d", &x, &y);
		unite(x, y);	
	}
	int ans = 0;
	for(int i = 1; i <= tot; i++) {
		par[i] = find(i);
		if(par[i] == i) ++ans;	
	}
	printf("%d", ans);
	return 0;	
}
发布了356 篇原创文章 · 获赞 12 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_45228537/article/details/104235499
今日推荐