题目链接:https://www.luogu.com.cn/problem/P1536
题目大意:告诉你一些点属于同一个集合,求最少连多少条边能够合成一个集合。
解题思路:
最少连边数 = 集合数 - 1。
实现代码如下:
#include<bits/stdc++.h> using namespace std; const int maxn = 10010; int n, m, f[maxn], cnt; bool vis[maxn]; int func_find(int x) { return x == f[x] ? x : f[x] = func_find(f[x]); } int func_union(int x, int y) { int a = func_find(x), b = func_find(y); f[a] = f[b] = f[x] = f[y] = min(a, b); } void init() { for (int i = 1; i <= n; i ++) f[i] = i; for (int i = 1; i <= n; i ++) vis[i] = false; cnt = 0; } int main() { while (cin >> n) { if (n == 0) break; cin >> m; init(); while (m --) { int x, y; cin >> x >> y; func_union(x, y); } for (int i = 1; i <= n; i ++) { int rt = func_find(i); if (!vis[rt]) { vis[rt] = true; cnt ++; } } cout << cnt-1 << endl; } return 0; }
来源:https://www.cnblogs.com/quanjun/p/12319082.html