标签:ace png info alt mes include using 它的 技术
https://www.luogu.com.cn/problem/P1536
这道题第一眼的思路感觉是最小生成树,但是发现它的边没有权值,所以这道题的问题是求解这个图的连通块的个数,而需要连接的道路条数就是连通块的个数减一
#include<iostream> #include<cstdio> #include<string> #include<cstring> using namespace std; int father[6000], ranks[6000]; int find(int x) { if (father[x] == x)return x; return father[x] = find(father[x]); } void merge(int x, int y) { int a = find(x); int b = find(y); if (a == b)return; if (ranks[a] > ranks[b])father[b] = a; else { father[a] = b; if (ranks[a] == ranks[b])ranks[b]++; } } int main() { int n, m; while (1) { cin >> n; if (n == 0)return 0; cin >> m; for (int i = 1; i <= n; i++)father[i] = i; for (int i = 0; i < m; i++) { int a, b; scanf("%d%d", &a, &b); merge(a, b); } int count = 0; for (int i = 1; i <=n; i++) { if (father[i] == i)count++; } printf("%d\n", count-1); } }
标签:ace png info alt mes include using 它的 技术
原文地址:https://www.cnblogs.com/Jason66661010/p/13205022.html