SWEA_D4_7465
π [D4_7465] μ°½μ© λ§μ 무리μ κ°μ
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class Solution {
static StringTokenizer st;
static int[] arr;
static int N;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
// ν
μ€νΈ μΌμ΄μ€ λ²νΈ
int tc = Integer.parseInt(br.readLine());
for(int T=1; T<=tc; T++){
sb.append("#").append(T).append(" ");
st = new StringTokenizer(br.readLine(), " ");
// μ¬λμ μ
N = Integer.parseInt(st.nextToken());
// κ΄κ³ μ
int M = Integer.parseInt(st.nextToken());
makeSet();
for(int i = 0; i<M; i++){
st = new StringTokenizer(br.readLine(), " ");
int start = Integer.parseInt(st.nextToken());
int end = Integer.parseInt(st.nextToken());
// μ§ν© ν©μΉκΈ°
unionSet(start, end);
}
// μ§ν© κ°μ ꡬνκΈ°
ArrayList<Integer> list = new ArrayList<Integer>();
for(int i=1; i<=N; i++){
int temp = findSet(i);
if(list.contains(temp)){
continue;
}
list.add(temp);
}
sb.append(list.size()).append("\n");
}
System.out.println(sb);
}
// μ¬λλ€ κ·Έλ£Ή μ μ
static void makeSet(){
arr = new int[N+1];
for(int i=1; i<=N; i++){
arr[i] = i;
}
}
static boolean unionSet(int a, int b){
int aRoot = findSet(a);
int bRoot = findSet(b);
if(aRoot == bRoot){
return false;
}
arr[bRoot] = aRoot;
return true;
}
static int findSet(int a){
if(a == arr[a]){
return a;
}
arr[a] = findSet(arr[a]);
return arr[a];
}
}
π€ λμ μκ°
μλ‘μ μ§ν©κ³Ό κ°μ λ¬Έμ μ΄λ€.
λ¨μ§ μλ‘μ μ§ν©μμ λΆλͺ¨λ
Έλλ€μ κ°μλ₯Ό ꡬν΄μ£Όλ©΄ λλ€. κ·Έκ²μ΄ μ§ν©μ μμ΄κΈ° λλ¬Έμ΄λ€.
μ§ν©μ ν©μΉκ±°λ 무리λ₯Ό ꡬνλ λ¬Έμ κ°μ κ²μ μλ‘μ μ§ν©μ ꡬνλ λ°©λ²κ³Ό κ°μ΄ νλ©΄ μ½κ² νλ¦°λ€.