Skip to content

Commit 201b070

Browse files
authored
Merge pull request #1009 from AlgorithmWithGod/lkhyun
[20250930] PGM / Lv3 / 합승 택시 요금 / 이강현
2 parents 96381de + 3dd8f77 commit 201b070

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
```java
2+
import java.util.*;
3+
4+
class Solution {
5+
static class Edge{
6+
int to,cost;
7+
Edge(int to, int cost){
8+
this.to = to;
9+
this.cost = cost;
10+
}
11+
}
12+
static List<Edge>[] adjList;
13+
static int[] distA;
14+
static int[] distB;
15+
static int[] distS;
16+
public int solution(int n, int s, int a, int b, int[][] fares) {
17+
int answer = 0;
18+
adjList = new List[n+1];
19+
for(int i = 1; i<=n; i++){
20+
adjList[i] = new ArrayList<>();
21+
}
22+
23+
for(int[] fare : fares){
24+
adjList[fare[0]].add(new Edge(fare[1],fare[2]));
25+
adjList[fare[1]].add(new Edge(fare[0],fare[2]));
26+
}
27+
28+
distA = new int[n+1];
29+
distB = new int[n+1];
30+
distS = new int[n+1];
31+
dijkstra(a,distA);
32+
dijkstra(b,distB);
33+
dijkstra(s,distS);
34+
35+
answer = distS[a] + distS[b];
36+
for(int i=1; i<=n; i++){
37+
answer = Math.min(answer, distS[i] + distA[i] + distB[i]);
38+
}
39+
return answer;
40+
}
41+
public void dijkstra(int start, int[] dist){
42+
PriorityQueue<Edge> pq = new PriorityQueue<>((a,b) -> Integer.compare(a.cost,b.cost));
43+
Arrays.fill(dist, Integer.MAX_VALUE);
44+
pq.offer(new Edge(start,0));
45+
dist[start] = 0;
46+
47+
while(!pq.isEmpty()){
48+
Edge cur = pq.poll();
49+
50+
if(dist[cur.to] < cur.cost) continue;
51+
52+
for(Edge next : adjList[cur.to]){
53+
int newDist = cur.cost + next.cost;
54+
if(newDist < dist[next.to]){
55+
dist[next.to] = newDist;
56+
pq.offer(new Edge(next.to,newDist));
57+
}
58+
}
59+
}
60+
}
61+
}
62+
```

0 commit comments

Comments
 (0)