알고리즘/SwExpert recipe

[SWEA] 서로소집합 D4

컵라면만두세트 2021. 3. 18. 23:22
package D4;

import java.util.Scanner;

public class 서로소집합 {
	static int n,m;
	static int parents[];
	
	static boolean union(int a, int b) {
		
		int aRoot = findset(a);
		int bRoot = findset(b);
		
		if(aRoot == bRoot) return false;
		
		parents[bRoot] = aRoot;
		
		return true;
		
	}
	static int findset(int a) {
		
		if(parents[a] == a) return a;
		parents[a] = findset(parents[a]);
		
		return parents[a];
	}
	static void make() {
		
		for(int i =0; i<n; i++) {
			parents[i] = i;
		}
		
	}
	
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int T =sc.nextInt();
		for(int tc =1; tc<=T; tc++) {
			n =sc.nextInt();
			m = sc.nextInt();
			parents = new int[n+1];
			
			make();
			System.out.print("#" + tc + " ");
			for(int i =0; i<m; i++) {
				int k = sc.nextInt();//연산자 0이면 union , 1이면 findset
				int a = sc.nextInt();
				int b = sc.nextInt();
				if(k==0) {
					union(a,b);
				}else if(k==1) {
					if(findset(a) == findset(b)) 
						System.out.print(1);
					else 
						System.out.print(0);
					
				}
			}
			System.out.println();
		}
	}
}

'알고리즘 > SwExpert recipe' 카테고리의 다른 글

[SWEA] String D3  (0) 2021.03.20
[SWEA] 석찬이의 받아쓰기 D3  (0) 2021.03.18
[SWEA] Summation D3  (0) 2021.03.18
[SWEA] 수영장 D3  (0) 2021.03.11
[SWEA] 코딩토너먼트1 [D3]  (0) 2021.03.11