【模板】并查集

并查集(路径压缩)

// luogu p3367 并查集板子
#include<bits/stdc++.h> using namespace std; int n, m, z, x, y; int f[10005]; int find(int x) { if(x == f[x]) return x; return f[x] = find(f[x]); // 路径压缩 } void hb(int x, int y) // 合并 { if(find(x) != find(y)) f[find(y)] = find(x); return ; } int main() { cin >> n >> m; for(int i = 1; i <= n; i++) f[i] = i; for(int i = 1; i <= m; i++) { cin >> z >> x >> y; if(z == 1) hb(x, y); else { if(find(x) == find(y)) cout << "Y" << endl; else cout << "N" << endl; } } return 0; }

 

posted @ 2019-09-12 19:34  ATKevin  阅读(124)  评论(0编辑  收藏  举报