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 }
View Code

 

posted @ 2016-04-06 20:59  cdongyang  阅读(395)  评论(0编辑  收藏  举报