Algorithm/SW Expert Academy

3289 서로소 집합

henry1214 2018. 2. 22. 23:36

https://www.swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AWBJKA6qr2oDFAWr&categoryId=AWBJKA6qr2oDFAWr&categoryType=CODE



유니온 파인드를 구현하자.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <cstdio>
 
int p[1000001];
int Find(int x) { return x==p[x]?x:p[x]=Find(p[x]); }
void Union(int x,int y) { p[Find(x)]=Find(y); }
 
int main()
{
    int t;
    scanf("%d",&t);
    for(int k=1;k<=t;k++)
    {
        printf("#%d ",k);
        int n,m;
        scanf("%d %d",&n,&m);
        for(int i=1;i<=n;i++) p[i]=i;
        while(m--)
        {
            int op,a,b;
            scanf("%d %d %d",&op,&a,&b);
            if(op==0) Union(a,b);
            else printf("%d",Find(a)==Find(b)?1:0);
        }
        printf("\n");
    }
    return 0;
}
cs