[模板]並查集
阿新 • • 發佈:2018-02-18
.org tps src color urn 分享 reg www pan
https://www.luogu.org/problemnew/show/P3367
//據說根本不用按秩合並,隨機將x合並到y/y合並到x就可以了
1 // luogu-judger-enable-o2 2 #include<bits/stdc++.h> 3 using namespace std; 4 5 #define lop(i,a,b) for(register int i = (a); i <= (b); ++i) 6 #define getchar() (*p1++) 7 char buf[3000004],*p1=buf; 8 const intView CodeN = 10005; 9 inline int read(){ 10 register int c = getchar(), x = 0; 11 while(!isdigit(c)) c = getchar(); 12 while(isdigit(c)) x = (x<<3)+(x<<1)+(c^48), c = getchar(); 13 return x; 14 } 15 int n, Q, fa[N], ch[300005]; 16 17 inline int find(int x){ 18 while(x!=fa[x])x=fa[x]=fa[fa[x]];return x; 19 } 20 21 int main(){ 22 fread(buf, 1, 3000000, stdin); 23 n = read(), Q = read(); 24 lop(i,1,n)fa[i]=i; 25 while(Q--){ 26 int opt = read(), x = read(), y = read(); 27 x = find(x), y = find(y); 28 if(opt == 1) fa[x] = y;29 else puts(x==y?"Y":"N"); 30 } 31 return 0; 32 }
[模板]並查集