forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path8.java
100 lines (82 loc) Β· 2.9 KB
/
8.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import java.util.*;
class Edge implements Comparable<Edge> {
private int distance;
private int nodeA;
private int nodeB;
public Edge(int distance, int nodeA, int nodeB) {
this.distance = distance;
this.nodeA = nodeA;
this.nodeB = nodeB;
}
public int getDistance() {
return this.distance;
}
public int getNodeA() {
return this.nodeA;
}
public int getNodeB() {
return this.nodeB;
}
// 거리(λΉμ©)κ° μ§§μ κ²μ΄ λμ μ°μ μμλ₯Ό κ°μ§λλ‘ μ€μ
@Override
public int compareTo(Edge other) {
if (this.distance < other.distance) {
return -1;
}
return 1;
}
}
public class Main {
// λ
Έλμ κ°μ(V)μ κ°μ (Union μ°μ°)μ κ°μ(E)
public static int v, e;
public static int[] parent = new int[100001]; // λΆλͺ¨ ν
μ΄λΈ μ΄κΈ°ν
// λͺ¨λ κ°μ μ λ΄μ 리μ€νΈμ, μ΅μ’
λΉμ©μ λ΄μ λ³μ
public static ArrayList<Edge> edges = new ArrayList<>();
public static int result = 0;
// νΉμ μμκ° μν μ§ν©μ μ°ΎκΈ°
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;
}
// λͺ¨λ κ°μ μ λν μ 보λ₯Ό μ
λ ₯ λ°κΈ°
for (int i = 0; i < e; i++) {
int a = sc.nextInt();
int b = sc.nextInt();
int cost = sc.nextInt();
// λΉμ©μμΌλ‘ μ λ ¬νκΈ° μν΄μ ννμ 첫 λ²μ§Έ μμλ₯Ό λΉμ©μΌλ‘ μ€μ
edges.add(new Edge(cost, a, b));
}
// κ°μ μ λΉμ©μμΌλ‘ μ λ ¬
Collections.sort(edges);
int last = 0; // μ΅μ μ μ₯ νΈλ¦¬μ ν¬ν¨λλ κ°μ μ€μμ κ°μ₯ λΉμ©μ΄ ν° κ°μ
// κ°μ μ νλμ© νμΈνλ©°
for (int i = 0; i < edges.size(); i++) {
int cost = edges.get(i).getDistance();
int a = edges.get(i).getNodeA();
int b = edges.get(i).getNodeB();
// μ¬μ΄ν΄μ΄ λ°μνμ§ μλ κ²½μ°μλ§ μ§ν©μ ν¬ν¨
if (findParent(a) != findParent(b)) {
unionParent(a, b);
result += cost;
last = cost;
}
}
System.out.println(result - last);
}
}