-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1197.java
More file actions
75 lines (59 loc) · 1.86 KB
/
1197.java
File metadata and controls
75 lines (59 loc) · 1.86 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/**
* 백준 1197번 최소 스패닝 트리
* 크루스칼 알고리즘
*/
import java.util.*;
import java.io.*;
class Edge{
int v;
int w;
int cost;
public Edge(int v, int w, int cost){
this.v = v;
this.w = w;
this.cost = cost;
}
}
public class Main {
static int root[] = new int[10001];
static int v;
static int e;
static int getParent(int v){
if(root[v]==v) return v;
return getParent(root[v]);
}
static void setUnion(int a, int b){
int rootA = getParent(a);
int rootB = getParent(b);
if(rootA<rootB) root[rootB] = rootA;
else root[rootA] = rootB;
}
static Boolean isCycle(int a, int b){
return (getParent(a)==getParent(b));
}
static int kruskal(List<Edge> graph){
int sum = 0;
for(int i=1; i<=v; i++)
root[i] = i; // 초기에는 자기 자신이 부모
for(Edge edge : graph){
if(!isCycle(edge.v, edge.w)){
sum += edge.cost;
setUnion(edge.v, edge.w);
}
}
return sum;
}
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine()," ");
v = Integer.parseInt(st.nextToken()); // 정점 개수
e = Integer.parseInt(st.nextToken()); // 간선 개수
List<Edge> graph = new ArrayList<>();
for(int i=0; i<e; i++){
st = new StringTokenizer(br.readLine()," ");
graph.add(new Edge(Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken())));
}
Collections.sort(graph, (e1,e2)-> Integer.compare(e1.cost,e2.cost));
System.out.println(kruskal(graph));
}
}