并查集
代码1:
#include <bits/stdc++.h> using namespace std; const int maxn = 1e5 + 10; int par[maxn]; int rank[maxn]; void init(int n) { for(int i = 0; i < n; i ++) { par[i] = i; rank[i] = 0; } } int find(int x) { if(par[x] == x) return x; else return par[x] = find(par[x]); } int unite(int x, int y) { x = find(x); y = find(y); if(x == y) return; if(rank[x] < rank[y]) par[x] = y; else { par[y] = x; if(rank[x] == rank[y]) rank[x] ++; } } bool same(int x, int y) { return find(x) == find(y); }
代码2:
#include <bits/stdc++.h> using namespace std; int N; int c; int fa[20]; int dfs(int z) { if(fa[z] == z) return z; else return fa[z] = dfs(fa[z]); } int main() { scanf("%d", &N); for(int i = 1; i <= N; i ++) fa[i] = i; while(N --) { int x, y; scanf("%d", &c); scanf("%d%d", &x, &y); if(c == 0) fa[y] = dfs(x); else if(c == 1) { if(dfs(x) == dfs(y)) printf("YES\n"); else printf("NO\n"); } } return 0; }
代码3:
#include <bits/stdc++.h> using namespace std; const int maxn = 1e5 + 10; int f[maxn]; int n; int Find(int x) { if(x != f[x]) f[x] = Find(f[x]); return f[x]; } void init() { for(int i = 1; i <= n; i ++) { f[i] = i; } } int Merge(int x, int y) { int fx = Find(x); int fy = Find(y); if(fx != fy) { f[fx] = fy; } } int main() { return 0; }