-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBOJ1922.java
More file actions
65 lines (56 loc) · 1.62 KB
/
BOJ1922.java
File metadata and controls
65 lines (56 loc) · 1.62 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
package ¹éÁØ;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
public class BOJ1922 {
static boolean[] visited;
static ArrayList<ArrayList<Node>> list = new ArrayList<>();
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
int M = Integer.parseInt(br.readLine());
int sum = 0;
StringTokenizer st;
visited = new boolean[N+1];
for(int i = 0; i <= N; i++) {
list.add(new ArrayList<>());
}
for(int i = 0; i < M; i++) {
st = new StringTokenizer(br.readLine());
int from = Integer.parseInt(st.nextToken());
int to = Integer.parseInt(st.nextToken());
int length = Integer.parseInt(st.nextToken());
list.get(from).add(new Node(to, length));
list.get(to).add(new Node(from, length));
}
PriorityQueue<Node> pq = new PriorityQueue<>();
pq.offer(new Node(1, 0));
while(!pq.isEmpty()) {
Node temp = pq.poll();
if(visited[temp.end]) continue;
sum += temp.weight;
visited[temp.end] = true;
for(Node ans : list.get(temp.end)) {
if(!visited[ans.end]) {
pq.offer(ans);
}
}
}
System.out.print(sum);
}
public static class Node implements Comparable<Node>{
int end;
int weight;
Node(int end, int weight){
this.end = end;
this.weight = weight;
}
@Override
public int compareTo(Node o) {
return weight - o.weight;
}
}
}