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);
}
}'코딩테스트 > JAVA' 카테고리의 다른 글
| [SWEA JAVA] 1251. [S/W 문제해결 응용] 4일차 - 하나로 (0) | 2024.08.29 |
|---|---|
| [SWEA JAVA] 3124. 최소 스패닝 트리 (0) | 2024.08.29 |
| [SWEA JAVA] 1238. [S/W 문제해결 기본] 10일차 - Contact (1) | 2024.08.28 |
| [백준 JAVA] 1941번: 소문난 칠공주 (0) | 2024.08.28 |
| [백준 JAVA] 11559번: Puyo Puyo (0) | 2024.08.27 |