村村通(并查集模板)
就是模板题:
#include<iostream> using namespace std; const int maxn = 1e3 + 10; int fa[maxn]; int getfa(int x){ if (fa[x] == x)return x; return fa[x] = getfa(fa[x]); } int find(int x, int y){ return getfa(x) == getfa(y); } void H_(int x, int y){ if (!find(x, y))fa[getfa(x)] = fa[getfa(y)]; } int n, m, x, y, ans; int main(){ while (cin >> n >> m){ ans = n - 1; for (int i = 1; i <= n; ++i) fa[i] = i; for (int i = 1; i <= m; ++i) { cin >> x >> y; if (find(x, y))continue; H_(x, y); ans--; } cout << ans << endl; } }