CodeForces 566D 并查集集合合并
Posted dy blog
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了CodeForces 566D 并查集集合合并相关的知识,希望对你有一定的参考价值。
1 #include <stdio.h> 2 #include <algorithm> 3 #define MAX 100000 4 #define LL long long 5 #define unsigned U 6 //using namespace std; 7 int cas=1,T; 8 int fa[MAX*2+10],next[MAX*2+10],n,q; 9 void init(int n) 10 { 11 for(int i=1;i<=n;i++) { fa[i]=i;next[i]=i+1; } 12 } 13 int find(int x) 14 { 15 return fa[x]==x?x:(fa[x]=find(fa[x])); 16 } 17 void merge(int x,int y) 18 { 19 if(x>y) std::swap(x,y); 20 for(int i=x+1;i<=y;) 21 { 22 int xx=find(i); 23 int yy=find(i-1); 24 fa[xx]=fa[yy]=std::min(xx,yy); 25 int tmp=next[i]; 26 next[i]=next[y]; 27 i=tmp; 28 } 29 } 30 int main() 31 { 32 //freopen("1.in","w",stdout); 33 //freopen("1.in","r",stdin); 34 //freopen("1.out","w",stdout); 35 //scanf("%d",&T); 36 while(scanf("%d%d",&n,&q)==2) 37 { 38 init(n); 39 int t,x,y; 40 while(q--) 41 { 42 scanf("%d%d%d",&t,&x,&y); 43 if(t==3) puts(find(x)==find(y)?"YES":"NO"); 44 else if(t==2) merge(x,y); 45 else 46 { 47 int xx=find(x); 48 int yy=find(y); 49 fa[xx]=fa[yy]=std::min(xx,yy); 50 } 51 } 52 } 53 //printf("time=%.3lf",(double)clock()/CLOCKS_PER_SEC); 54 return 0; 55 }
以上是关于CodeForces 566D 并查集集合合并的主要内容,如果未能解决你的问题,请参考以下文章
Codeforces 1263D. Secret Passwords(并查集,思维)
Codeforces 722C Destroying Array(并查集)*
Codeforces Round #396 (Div. 2)D. Mahmoud and a Dictionary(带权并查集)
Codeforces Round #396 (Div. 2)D. Mahmoud and a Dictionary(带权并查集)