Skip to content

Commit 39f2bc8

Browse files
authored
Merge pull request #1719 from AlgorithmWithGod/LiiNi-coder
[20251220] BOJ / G4 / 특정한 최단 경로 / 이인희
2 parents 09580a8 + 13297a2 commit 39f2bc8

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
```java
2+
import java.io.*;
3+
import java.util.*;
4+
5+
public class Main {
6+
static class Edge {
7+
int to;
8+
int cost;
9+
Edge(int to, int cost){
10+
this.to = to;
11+
this.cost = cost;
12+
}
13+
}
14+
15+
static final int INF = 100_000_000;
16+
static ArrayList<Edge>[] Graph;
17+
18+
public static void main(String[] args) throws IOException {
19+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
20+
StringTokenizer st = new StringTokenizer(br.readLine());
21+
int N = Integer.parseInt(st.nextToken());
22+
int E = Integer.parseInt(st.nextToken());
23+
24+
Graph = new ArrayList[N + 1];
25+
for(int i = 1; i <= N; i++){
26+
Graph[i] = new ArrayList<>();
27+
}
28+
for(int i = 0; i < E; i++){
29+
st = new StringTokenizer(br.readLine());
30+
int a = Integer.parseInt(st.nextToken());
31+
int b = Integer.parseInt(st.nextToken());
32+
int c = Integer.parseInt(st.nextToken());
33+
Graph[a].add(new Edge(b, c));
34+
Graph[b].add(new Edge(a, c));
35+
}
36+
st = new StringTokenizer(br.readLine());
37+
int A = Integer.parseInt(st.nextToken());
38+
int B = Integer.parseInt(st.nextToken());
39+
int[] dist1 = dikstra(1, N);
40+
int[] distA = dikstra(A, N);
41+
int[] distB = dikstra(B, N);
42+
43+
long path1 = (long)dist1[A] + distA[B] + distB[N];
44+
long path2 = (long)dist1[B] + distB[A] + distA[N];
45+
long answer = Math.min(path1, path2);
46+
System.out.println((answer >= INF) ? -1 : answer);
47+
}
48+
49+
private static int[] dikstra(int start, int N){
50+
int[] dist = new int[N + 1];
51+
Arrays.fill(dist, INF);
52+
dist[start] = 0;
53+
54+
PriorityQueue<int[]> pq = new PriorityQueue<>(
55+
(a, b) -> a[1] - b[1]
56+
);
57+
pq.offer(new int[]{start, 0});
58+
59+
while(!pq.isEmpty()){
60+
int[] cur = pq.poll();
61+
int now = cur[0];
62+
int cost = cur[1];
63+
64+
if(cost > dist[now])
65+
continue;
66+
67+
for(Edge e : Graph[now]){
68+
int next = e.to;
69+
int nextCost = cost + e.cost;
70+
if(nextCost < dist[next]){
71+
dist[next] = nextCost;
72+
pq.offer(new int[]{next, nextCost});
73+
}
74+
}
75+
}
76+
return dist;
77+
}
78+
}
79+
80+
```

0 commit comments

Comments
 (0)