基础并查集。
#include <cstdio> #include <cstring> #define maxn 1000 + 5 using namespace std; int p[maxn]; void init(int n){ for (int i = 1; i <= n; i++) p[i] = i; } int Find(int x){ return p[x] == x ? x : (p[x] = Find(p[x])); } void Join(int x, int y){ int fx = Find(x), fy = Find(y); if (fx != fy) p[fx] = fy; } int main(){ int n, m; while (scanf("%d", &n) && n){ scanf ("%d", &m); init(n); for (int i = 0; i < m; i++){ int temp1, temp2; scanf("%d %d", &temp1, &temp2); Join(temp1, temp2); } int ans = 0; for (int i = 1; i <= n; i++) if (Find(i) == i) ans++; printf("%d ", ans - 1); } return 0; }