forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path3.java
More file actions
57 lines (47 loc) ยท 1.7 KB
/
3.java
File metadata and controls
57 lines (47 loc) ยท 1.7 KB
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 parent[x] = 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();
}
}