Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit ae16460

Browse files
authoredFeb 17, 2025
Create PG_합승택시요금.java
1 parent 5948c51 commit ae16460

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed
 

‎250217/PG_합승택시요금.java

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
/**
2+
* 프로그래머스 합승 택시 요금
3+
* - 다익스트라!!!!
4+
*/
5+
6+
import java.util.*;
7+
8+
class Solution {
9+
class Node implements Comparable<Node> {
10+
int node, value;
11+
12+
Node (int node, int value) {
13+
this.node = node;
14+
this.value = value;
15+
}
16+
17+
@Override
18+
public int compareTo(Node o) {
19+
return Integer.compare(this.value, o.value);
20+
}
21+
}
22+
23+
List<Node> list[];
24+
int[] dist;
25+
int len;
26+
27+
public int solution(int n, int s, int a, int b, int[][] fares) {
28+
len = n;
29+
30+
list = new ArrayList[n + 1];
31+
for (int i = 0; i <= n; i++) {
32+
list[i] = new ArrayList<>();
33+
}
34+
35+
for (int i = 0; i < fares.length; i++) {
36+
list[fares[i][0]].add(new Node(fares[i][1], fares[i][2]));
37+
list[fares[i][1]].add(new Node(fares[i][0], fares[i][2]));
38+
}
39+
40+
int[] together = dijkstra(s);
41+
int[] aloneA = dijkstra(a);
42+
int[] aloneB= dijkstra(b);
43+
int cost = Integer.MAX_VALUE;
44+
45+
for (int i = 1; i <= n; i++) {
46+
if (together[i] == Integer.MAX_VALUE || aloneA[i] == Integer.MAX_VALUE || aloneB[i] == Integer.MAX_VALUE) continue;
47+
48+
cost = Math.min(cost, together[i] + aloneA[i] + aloneB[i]);
49+
}
50+
51+
return cost;
52+
}
53+
54+
public int[] dijkstra(int s) {
55+
dist = new int[len + 1];
56+
Arrays.fill(dist, Integer.MAX_VALUE);
57+
dist[s] = 0;
58+
59+
PriorityQueue<Node> queue = new PriorityQueue<>();
60+
queue.add(new Node(s, 0));
61+
62+
while (!queue.isEmpty()) {
63+
Node cur = queue.poll();
64+
int node = cur.node;
65+
int value = cur.value;
66+
67+
if (dist[node] < value) continue;
68+
69+
for (int i = 0; i < list[node].size(); i++) {
70+
int nextN = list[node].get(i).node;
71+
int nextV = list[node].get(i).value;
72+
73+
if (dist[nextN] > value + nextV) {
74+
queue.add(new Node(nextN, value + nextV));
75+
dist[nextN] = value + nextV;
76+
}
77+
}
78+
}
79+
80+
return dist;
81+
}
82+
}

0 commit comments

Comments
 (0)
Please sign in to comment.