반응형
https://programmers.co.kr/learn/courses/30/lessons/72413
코딩테스트 연습 - 합승 택시 요금
6 4 6 2 [[4, 1, 10], [3, 5, 24], [5, 6, 2], [3, 1, 41], [5, 1, 24], [4, 6, 50], [2, 4, 66], [2, 3, 22], [1, 6, 25]] 82 7 3 4 1 [[5, 7, 9], [4, 6, 4], [3, 6, 1], [3, 2, 3], [2, 1, 6]] 14 6 4 5 6 [[2,6,6], [6,3,7], [4,6,7], [6,5,11], [2,5,12], [5,3,20], [2,4
programmers.co.kr
다익스트라를 이용하여 풀었습니다.
특정한 i 지점에서 내린다고 했을 때,
(S -> i 까지의 최소 비용) + (i -> A 까지의 최소 비용) + (i -> B 까지의 최소 비용) 의 최솟값을 구해주었습니다.
S == i일 때가 합승을 하지 않는 상황입니다.
#include <string>
#include <vector>
#include <queue>
#include <algorithm>
#define INF 666666666
using namespace std;
vector<vector<pair<int, int>>> graph(201, vector<pair<int, int>>());
vector<int> dijkstra(int n, int start) {
priority_queue<pair<int, int>> pq;
vector<int> fare(n+1, INF);
fare[start] = 0;
pq.push({0, start});
while(!pq.empty()) {
int cost = -pq.top().first;
int pos = pq.top().second;
pq.pop();
if(cost > fare[pos]) continue;
for(int i=0; i<graph[pos].size(); i++) {
int nextPos = graph[pos][i].first;
int nextCost = cost + graph[pos][i].second;
if(fare[nextPos] > nextCost) {
fare[nextPos] = nextCost;
pq.push({-nextCost, nextPos});
}
}
}
return fare;
}
int solution(int n, int s, int a, int b, vector<vector<int>> fares) {
int ans = INF;
for(int i=0; i<fares.size(); i++) {
int a = fares[i][0];
int b = fares[i][1];
int f = fares[i][2];
graph[a].push_back({b, f});
graph[b].push_back({a, f});
}
vector<int> sFare = dijkstra(n, s);
vector<int> aFare = dijkstra(n, a);
vector<int> bFare = dijkstra(n, b);
for(int i=1; i<= n; i++)
ans = min(ans, sFare[i] + aFare[i] + bFare[i]);
return ans;
}
반응형
'Algorithm' 카테고리의 다른 글
백준 1939 : 중량제한 (0) | 2021.11.14 |
---|---|
백준 1946 : 신입 사원 (0) | 2021.11.14 |
프로그래머스 : 디스크 컨트롤러 (0) | 2021.11.14 |
프로그래머스 : 더 맵게 (0) | 2021.11.14 |
프로그래머스 : 카펫 (0) | 2021.11.14 |