본문 바로가기

코딩테스트/JAVA

[SWEA JAVA] 7465. 창용 마을 무리의 개수

https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AWngfZVa9XwDFAQU

 

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

public class Main {
	public static int T, N, M, ans = 0;
	public static int[] arr, size;

	public static void make() {
		for (int i = 1; i < N + 1; i++) {
			arr[i] = i;
		}
	}

	public static void Union(int a, int b) {
		int aRoot = findSet(a);
		int bRoot = findSet(b);
		if (aRoot == bRoot)
			return;
		if (size[aRoot] > size[bRoot])
			arr[bRoot] = aRoot;
		else if (size[aRoot] == size[bRoot])
			size[bRoot]++;

		if (size[bRoot] > size[aRoot]) {
			arr[aRoot] = bRoot;
		}
		ans--;
	}

	public static int findSet(int a) {
		if (a == arr[a])
			return a;
		arr[a] = findSet(arr[a]);
		return arr[a];
	}

	public static int check(int a, int b) {
		int aRoot = findSet(a);
		int bRoot = findSet(b);
		if (aRoot == bRoot)
			return 1;
		else
			return 0;
	}

	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st;
		StringBuilder sb = new StringBuilder();
		T = Integer.parseInt(br.readLine());
		for (int tc = 1; tc <= T; tc++) {
			sb.append("#" + tc + " ");

			st = new StringTokenizer(br.readLine());
			N = Integer.parseInt(st.nextToken());
			M = Integer.parseInt(st.nextToken());

			arr = new int[N + 1];
			size = new int[N + 1];
			ans = N;
			make();

			for (int i = 0; i < M; i++) {
				st = new StringTokenizer(br.readLine());
				int a = Integer.parseInt(st.nextToken());
				int b = Integer.parseInt(st.nextToken());

				Union(a, b);
			}

			sb.append(ans + "\n");

		}
		System.out.println(sb);
	}
}