Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
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 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

코드와이

[SW Expert Academy] 7465. 창용 마을 무리의 개수 본문

SW_Expert

[SW Expert Academy] 7465. 창용 마을 무리의 개수

코드와이 2021. 4. 27. 22:52

 

문제링크

swexpertacademy.com/main/code/problem/problemDetail.do?problemLevel=4&contestProbId=AWngfZVa9XwDFAQU&categoryId=AWngfZVa9XwDFAQU&categoryType=CODE&problemTitle=&orderBy=PASS_RATE&selectCodeLang=JAVA&select-1=4&pageSize=10&pageIndex=5

 

SW Expert Academy

SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!

swexpertacademy.com

 

package D4;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class 창용_마을_무리의_개수 {

	static int n, m, arr[];
	
	public static void main(String[] args) throws NumberFormatException, IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringBuilder sb = new StringBuilder();
		StringTokenizer st;
		
		int T = Integer.parseInt(br.readLine());
		
		for(int tc = 1; tc <= T; tc++) {
			sb.append("#").append(tc).append(" ");
			
			st = new StringTokenizer(br.readLine());
			
			n = Integer.parseInt(st.nextToken());
			m = Integer.parseInt(st.nextToken());
			arr = new int[n+1];
			
			make();
			int ans = n;
			for(int i = 0 ; i < m ; i++) {
				st = new StringTokenizer(br.readLine());
				int f = Integer.parseInt(st.nextToken());
				int t = Integer.parseInt(st.nextToken());
				if(union(f, t)) {
					ans--;
				}
			}
			sb.append(ans).append("\n");
		}
		sb.setLength(sb.length()-1);
		System.out.println(sb);
	}
	
	public static void make() {
		for(int i = 1 ; i <= n ; i++) {
			arr[i] = i;
		}
	}
	
	public static int findSet(int a) {
		if(arr[a] == a) {
			return a;
		}
		return arr[a] = findSet(arr[a]);
	}
	
	public static boolean union(int a, int b) {
		int aSet = findSet(a);
		int bSet = findSet(b);
		
		if(aSet == bSet) return false;
		
		arr[bSet] = aSet;
		return true;
	}
	
}