Close
Close full mode
logo만렙 개발자 키우기

합승 택시 요금

Git RepositoryEdit on Github
Last update: a year ago by nowwaterReading time: 2 min

문제

코드

코드 보기
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Scanner;
class Edge{
int dst, cost;
public Edge(int dst, int cost) {
this.dst = dst;
this.cost = cost;
}
}
class Solution {
static int ans = 987654321;
static int dist[], dp[][];
static List<Edge> adj[];
public static int solution(int n, int s, int a, int b, int[][] fares) {
dist = new int[n + 1];
Arrays.fill(dist, 987654321);
adj = new List[n + 1];
dp = new int[n + 1][n + 1];
for (int i = 0; i <= n; i++) {
adj[i] = new ArrayList<>();
Arrays.fill(dp[i], 987654321);
}
for (int[] fare : fares) {
int u = fare[0];
int v = fare[1];
int c = fare[2];
dp[u][v] = dp[v][u] = c;
adj[u].add(new Edge(v, c));
adj[v].add(new Edge(u, c));
}
getFloyd(n);
dijkstra(s, a, b);
return ans;
}
private static void getFloyd(int n) {
for (int k = 1; k <= n ; k++) {
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if(i == j) dp[i][j] = 0;
else{
if(dp[i][j] > dp[i][k] + dp[k][j])
dp[i][j] = dp[i][k] + dp[k][j];
}
}
}
}
}
private static void dijkstra(int s, int a, int b) {
PriorityQueue<Edge> pq = new PriorityQueue<>((c, d) -> (c.cost - d.cost));
pq.add(new Edge(s, 0));
dist[s] = 0;
while (!pq.isEmpty()) {
Edge now = pq.poll();
int cur = now.dst, curCost = now.cost;
if(dist[cur] < curCost) continue;
ans = Math.min(ans, curCost + dp[cur][a] + dp[cur][b]);
for (Edge edge : adj[cur]) {
int next = edge.dst;
int nextCost = edge.cost;
if(dist[next] > curCost + nextCost){
dist[next] = curCost + nextCost;
pq.add(new Edge(next, dist[next]));
}
}
}
}
}

⭐️느낀점⭐️

앞선 문제들에 비해 문제를 해결하는 것이 수월했다.

그래프 관련 문제는 많이 풀어봐서 익숙했던 것이 컸던 것 같다.

풀고나서 다른 사람들 풀이를 봤는데, 굳이 다익스트라로 최단 경로 이동하면서 목적지까지 다시 최단경로를 쓸 필요가 없을 것 같다

나는 다익스트라 + 플로이드를 모두 사용했는데, 둘 중 하나만 사용해도 해결이 가능하다.

풀이 📣


1️⃣ 플로이드 와샬 알고리즘을 사용해서 모든 지점간에 최단 경로를 구해 놓는다

2️⃣ 시작점에서 인접한 지점 중 가장 비용이 최소로 하는 지점부터 이동해서 그 자리에서 목적지까지의 최소 비용을 구한다.

- 최소 힙을 이용해 비용이 가장 적은 간선을 선택해 이동한다.
- 이동한 지점에서 목적지까지 플로이드 알고리즘을 사용해 구해놓은 최단 경로를 통해 최소 비용을 구한다.
- 최소 택시 합승 비용과 비교해서 최소값을 유지한다.

3️⃣ 위의 과정을 반복해서 모든 지점까지의 최소 비용으로 이동한 후, 그곳에서 목적지까지 또 최소비용을 구한다.

4️⃣ 최종적으로 구한 최소비용을 출력한다.


👩‍💻 Problem Solving — Previous
순위 검색
Next — 👩‍💻 Problem Solving
광고 삽입