forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path1.java
57 lines (47 loc) Β· 1.69 KB
/
1.java
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import java.util.*;
public class Main {
// λ
Έλμ κ°μ(V)μ κ°μ (Union μ°μ°)μ κ°μ(E)
// λ
Έλμ κ°μλ μ΅λ 100,000κ°λΌκ³ κ°μ
public static int v, e;
public static int[] parent = new int[100001]; // λΆλͺ¨ ν
μ΄λΈ μ΄κΈ°ννκΈ°
// νΉμ μμκ° μν μ§ν©μ μ°ΎκΈ°
public static int findParent(int x) {
// λ£¨νΈ λ
Έλκ° μλλΌλ©΄, λ£¨νΈ λ
Έλλ₯Ό μ°Ύμ λκΉμ§ μ¬κ·μ μΌλ‘ νΈμΆ
if (x == parent[x]) return x;
return findParent(parent[x]);
}
// λ μμκ° μν μ§ν©μ ν©μΉκΈ°
public static void unionParent(int a, int b) {
a = findParent(a);
b = findParent(b);
if (a < b) parent[b] = a;
else parent[a] = b;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
v = sc.nextInt();
e = sc.nextInt();
// λΆλͺ¨ ν
μ΄λΈμμμ, λΆλͺ¨λ₯Ό μκΈ° μμ μΌλ‘ μ΄κΈ°ν
for (int i = 1; i <= v; i++) {
parent[i] = i;
}
// Union μ°μ°μ κ°κ° μν
for (int i = 0; i < e; i++) {
int a = sc.nextInt();
int b = sc.nextInt();
unionParent(a, b);
}
// κ° μμκ° μν μ§ν© μΆλ ₯νκΈ°
System.out.print("κ° μμκ° μν μ§ν©: ");
for (int i = 1; i <= v; i++) {
System.out.print(findParent(i) + " ");
}
System.out.println();
// λΆλͺ¨ ν
μ΄λΈ λ΄μ© μΆλ ₯νκΈ°
System.out.print("λΆλͺ¨ ν
μ΄λΈ: ");
for (int i = 1; i <= v; i++) {
System.out.print(parent[i] + " ");
}
System.out.println();
}
}