【模板】并查集
P3367 【模板】并查集
#include <iostream> #include <cstring> using namespace std; const int N = 1e4 + 10; int p[N], n, m; int find(int x) { if(p[x] != x) p[x] = find(p[x]); return p[x]; } int main() { cin >> n >> m; for(int i = 1; i <= n; i ++) p[i] = i; while(m --) { int z, a, b; cin >> z >> a >> b; int x = find(a), y = find(b); if(z == 1) { if(x != y) { p[x] = y; } } // 注意这里大括号不能省略,否在下面的else就跟if(x != y)匹配了,导致没有输出 else if(z == 2) { if(x == y) cout << "Y" << endl; else cout << "N" << endl; } } }