[swexpert] 3289. 서로소 집합 (java, union-find 함수)
728x90
반응형
import java.util.Scanner;
public class Solution {
static int t,n,m;
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
t=sc.nextInt();
for (int tc = 1; tc <=t; tc++) {
n=sc.nextInt();
m=sc.nextInt();
int parent[]=new int[n+1];
for(int i=1;i<=n;i+=1) {
parent[i]=i;
}
System.out.print("#"+tc+" ");
for (int i = 0; i < m; i++) {
int command=sc.nextInt();
int a=sc.nextInt();
int b=sc.nextInt();
if(command==1) {
if(find(parent,a,b)) {
System.out.print("1");
}else {
System.out.print("0");
}
}else {
union(parent,a,b);
}
}
System.out.println();
}
}
public static int findSet(int[] p,int x) {
if(x==p[x])return x;//부모
else return p[x]=findSet(p,p[x]);
}
public static void union(int[] p,int x,int y) {
x=findSet(p,x);
y=findSet(p,y);
if(x>y)p[x]=y;
else p[y]=x;
}
public static boolean find(int[] p,int x,int y) {
return findSet(p,x)==findSet(p,y);
}
}
728x90
반응형
'swexpert' 카테고리의 다른 글
[swexpert] 3282. 0/1 knapsack (dp, java) (0) | 2021.03.23 |
---|---|
[정보올림피아드] 1863. 종료 (Union-find, 시간제한) (0) | 2021.03.18 |
[swexpert] 1238. Contact (java, bfs) (0) | 2021.03.16 |
[swexpert] 7733. 치즈 도둑 (bfs, java) (0) | 2021.03.08 |
[swexpert] 1226. 미로 1 (bfs, java) (0) | 2021.03.08 |
TAGS.