并查集

 

 1 #include <iostream>
 2 
 3 using namespace std;
 4 
 5 const int MAXN=10010;
 6 
 7 int n,m;
 8 int head[MAXN];
 9 
10 int root(int x)   //寻找根
11 {
12     if (head[x]==x) return x;
13     else return head[x]=root(head[x]);
14 }
15 
16 int main()
17 {
18     cin>>n>>m;
19     for (int i=1;i<MAXN;i++) head[i]=i;   //init
20 
21     int z,x,y;
22     for (int i=1;i<=m;i++)
23     {
24         cin>>z>>x>>y;
25         if (z==1) head[root(x)]=root(y);   //合并Union
26         else
27         {
28             if (root(x)==root(y))   cout<<'Y'<<endl;   //查询
29             else    cout<<'N'<<endl;
30         }
31     }
32     return 0;
33 }

 

posted @ 2021-10-27 20:31  Hell0er  阅读(10)  评论(0编辑  收藏  举报