티스토리 뷰

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


'Algorithm > SW Expert Academy' 카테고리의 다른 글

2105 디저트 카페  (2) 2018.03.17
1953 탈주범 검거  (0) 2018.03.16
1952 수영장  (0) 2018.03.14
1949 등산로 조성  (4) 2018.03.14
1767 프로세서 연결하기  (2) 2018.02.14
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday