ç¡åã°ã©ãã®é£çµæåã®åæ°ãæ°ããåé¡
å顿¦è¦
é ç¹æ° ã辺æ°
ã®ç¡åã°ã©ããä¸ããããããã®ã°ã©ãã«ããã¤ãã®è¾ºãæ°ãã«è¿½å ãããã¨ã«ãã£ã¦ãã°ã©ãå
¨ä½ãé£çµã¨ãªãããã«ãããã
追å ãã¹ãè¾ºã®æ¬æ°ã®æå°å¤ãæ±ããã
å¶ç´
èãããã¨
ã°ã©ãã®é£çµæåã®åæ°ãæ±ãã¦ã1 ãå¼ãã°ãããã°ã©ãã®é£çµæåã®åæ°ãæ±ããã®ã¯
- Union-Find ã使ã
- DFS ãã
- BFS ãã
ãªã©ã®æ¹æ³ããããã©ãã§ãã£ã¦ãè§£ããã以ä¸ã®å®è£ ã§ã¯ Union-Find ãç¨ããã
#include <bits/stdc++.h> using namespace std; struct UnionFind { vector<int> par; UnionFind() { } UnionFind(int n) : par(n, -1) { } void init(int n) { par.assign(n, -1); } int root(int x) { if (par[x] < 0) return x; else return par[x] = root(par[x]); } bool issame(int x, int y) { return root(x) == root(y); } bool merge(int x, int y) { x = root(x); y = root(y); if (x == y) return false; if (par[x] > par[y]) swap(x, y); // merge technique par[x] += par[y]; par[y] = x; return true; } int size(int x) { return -par[root(x)]; } }; int main() { int N, M; cin >> N >> M; UnionFind uf(N); for (int i = 0; i < M; ++i) { int u, v; cin >> u >> v; --u, --v; uf.merge(u, v); } int res = 0; for (int i = 0; i < N; ++i) if (uf.root(i) == i) ++res; cout << res-1 << endl; }