/
BAEKJOON 5972
59 lines (53 loc) · 1.61 KB
/
BAEKJOON 5972
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
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
public class Main {
static int N, M;
static ArrayList<ArrayList<Edge>> list = new ArrayList<>();
static PriorityQueue<Edge> pq = new PriorityQueue<>((a,b) -> a.value - b.value);
static boolean[] visit;
static int[] cost;
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
N =Integer.parseInt(st.nextToken());
M =Integer.parseInt(st.nextToken());
visit = new boolean[N+1];
cost = new int[N+1];
for (int i = 0; i <=N; i++) {
list.add(new ArrayList<>());
cost[i] = Integer.MAX_VALUE;
}
for (int i = 0; i <M; i++) {
st = new StringTokenizer(br.readLine());
int s = Integer.parseInt(st.nextToken());
int e = Integer.parseInt(st.nextToken());
int v = Integer.parseInt(st.nextToken());
list.get(s).add(new Edge(e,v));
list.get(e).add(new Edge(s,v));
}
pq.offer(new Edge(1,0));
cost[1] = 0;
while(!pq.isEmpty()) {
Edge here = pq.poll();
if(visit[here.next]) continue;
visit[here.next] = true;
for (Edge last : list.get(here.next)) {
if(last.value + cost[here.next]< cost[last.next]) {
cost[last.next] = last.value + cost[here.next];
pq.offer(new Edge(last.next,cost[last.next]));
}
}
}
System.out.println(cost[N]);
}
static class Edge{
int next, value;
public Edge(int n, int v) {
this.next = n;
this.value = v;
}
}
}