题目链接:
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;
}
原文链接: https://www.cnblogs.com/yuhan-blog/p/12308612.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;
也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/328243
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!