Skip to content

Commit 6aaed4b

Browse files
authored
Merge pull request #486 from AlgorithmWithGod/JHLEE325
[20250717] BOJ / G4 / 특정한 최단 경로 / 이준희
2 parents cf8affd + f69c63b commit 6aaed4b

File tree

1 file changed

+91
-0
lines changed

1 file changed

+91
-0
lines changed
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
```java
2+
import java.io.BufferedReader;
3+
import java.io.InputStreamReader;
4+
import java.util.*;
5+
6+
public class Main {
7+
static int n, e;
8+
static List<List<Node>> list = new ArrayList<>();
9+
static final int INF = 987654321;
10+
11+
public static void main(String[] args) throws Exception {
12+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
13+
StringTokenizer st = new StringTokenizer(br.readLine());
14+
15+
n = Integer.parseInt(st.nextToken());
16+
e = Integer.parseInt(st.nextToken());
17+
18+
for (int i = 0; i <= n; i++)
19+
list.add(new ArrayList<>());
20+
21+
for (int i = 0; i < e; i++) {
22+
st = new StringTokenizer(br.readLine());
23+
int from = Integer.parseInt(st.nextToken());
24+
int to = Integer.parseInt(st.nextToken());
25+
int cost = Integer.parseInt(st.nextToken());
26+
list.get(from).add(new Node(to, cost));
27+
list.get(to).add(new Node(from, cost));
28+
}
29+
30+
st = new StringTokenizer(br.readLine());
31+
int v1 = Integer.parseInt(st.nextToken());
32+
int v2 = Integer.parseInt(st.nextToken());
33+
34+
int[] dist1 = dijkstra(1);
35+
int[] distv1 = dijkstra(v1);
36+
int[] distv2 = dijkstra(v2);
37+
38+
int path1 = dist1[v1] + distv1[v2] + distv2[n];
39+
int path2 = dist1[v2] + distv2[v1] + distv1[n];
40+
41+
if (dist1[v1] >= INF || distv1[v2] >= INF || distv2[n] >= INF) path1 = INF;
42+
if (dist1[v2] >= INF || distv2[v1] >= INF || distv1[n] >= INF) path2 = INF;
43+
44+
int result = Math.min(path1, path2);
45+
46+
if (result >= INF)
47+
System.out.println("-1");
48+
else System.out.println(result);
49+
}
50+
51+
static int[] dijkstra(int start) {
52+
int[] dist = new int[n + 1];
53+
Arrays.fill(dist, INF);
54+
dist[start] = 0;
55+
56+
PriorityQueue<Node> pq = new PriorityQueue<>();
57+
pq.offer(new Node(start, 0));
58+
59+
while (!pq.isEmpty()) {
60+
Node cur = pq.poll();
61+
int now = cur.idx;
62+
63+
if (cur.cost > dist[now]) continue;
64+
65+
for (Node next : list.get(now)) {
66+
if (dist[next.idx] > dist[now] + next.cost) {
67+
dist[next.idx] = dist[now] + next.cost;
68+
pq.offer(new Node(next.idx, dist[next.idx]));
69+
}
70+
}
71+
}
72+
73+
return dist;
74+
}
75+
76+
public static class Node implements Comparable<Node> {
77+
int idx, cost;
78+
79+
Node(int idx, int cost) {
80+
this.idx = idx;
81+
this.cost = cost;
82+
}
83+
84+
@Override
85+
public int compareTo(Node o) {
86+
return Integer.compare(this.cost, o.cost);
87+
}
88+
}
89+
}
90+
91+
```

0 commit comments

Comments
 (0)