SWEA_D4_3289
π [D4_3289] μλ‘μ μ§ν©
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Solution {
static StringTokenizer st;
static int[] arr;
static int n, m;
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++) {
st = new StringTokenizer(br.readLine(), " ");
sb.append("#").append(T).append(" ");
// μ§ν© μ
n = Integer.parseInt(st.nextToken());
// μ°μ°μ κ°μ
m = Integer.parseInt(st.nextToken());
makeSet();
for (int i = 0; i < m; i++) {
st = new StringTokenizer(br.readLine(), " ");
int cal = Integer.parseInt(st.nextToken());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
// ν©μ§ν©
if (cal == 0) {
unionSet(a, b);
}
// νμΈ
else if (cal == 1) {
if (findSet(a) == findSet(b)) {
sb.append(1);
} else {
sb.append(0);
}
}
}
sb.append("\n");
}
System.out.println(sb);
}
static void makeSet(){
arr = new int[n+1];
for(int i=1; i<=n; i++){
arr[i] = i;
}
}
// a μ§λ¨κ³Ό b μ§λ¨ ν©μΉκΈ° -> 0
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;
}
// aκ° ν¬ν¨λ λνμ μ°ΎκΈ° -> 1
static int findSet(int a) {
if (a == arr[a]) {
return a;
}
// κ²½λ‘ μμΆ
arr[a] = findSet(arr[a]);
// νμ¬μμΉμ λΆλͺ¨κ° λ°ν
return arr[a];
}
}
π€ λμ μκ°
μλ‘μ μ§ν© ꡬνκΈ° λ¬Έμ μ΄λ€.
Disjoint - set . makeSet()μ μ΅μ λ¨μ μ§ν©μ μμ±νκ³ findSet() μ μ§ν©μ μ°Ύκ³ ( μ§ν© λνμ μ°ΎκΈ° ) union()μ μ§ν©μ ν©μΉλ κ²μ΄λ€.
κ°κ° λ©μλλ₯Ό ꡬννμ¬ μ°μ°μ νμΈνμ¬ κ·Έμ λ§κ² 1μΌ λ κ°μ μ§ν©μ μλμ§ νμΈμ ν΄μ£Όμ΄μ μΆλ ₯ν΄μ£Όλ©΄ λλ€.
μλ‘μ μ§ν© μκ³ λ¦¬μ¦μ μ΄μ©νλ μ νμ μΈ λ¬Έμ μ΄λ€.