PS/BOJ
[알고리즘] 백준 5792번: 택배 배송 (C++)
도비(Doby)
2021. 12. 6. 01:48
https://www.acmicpc.net/problem/5972
5972번: 택배 배송
농부 현서는 농부 찬홍이에게 택배를 배달해줘야 합니다. 그리고 지금, 갈 준비를 하고 있습니다. 평화롭게 가려면 가는 길에 만나는 모든 소들에게 맛있는 여물을 줘야 합니다. 물론 현서는
www.acmicpc.net
문제를 읽고, 그래프가 양방향 그래프인 것을 알고 다익스트라를 돌리면 된다.
#include <iostream>
#include <queue>
#include <utility>
#include <vector>
#define MAX 50000 + 1
#define INF 987654321
#define pii pair<int, int>
using namespace std;
int n, m;
vector<pii> graph[MAX];
int dist[MAX];
struct cmp {
bool operator()(pii& a, pii& b) {
return a.second > b.second;
}
};
void dijkstra(int node) {
dist[node] = 0;
priority_queue<pii, vector<pii>, cmp> pq;
pq.push({ node, 0 });
while (!pq.empty()) {
int now = pq.top().first;
int cost = pq.top().second;
pq.pop();
if(dist[now] < cost){
continue;
}
for (int i = 0; i < graph[now].size(); i++) {
int next = graph[now][i].first;
int nextCost = graph[now][i].second;
if (cost + nextCost < dist[next]) {
dist[next] = cost + nextCost;
pq.push({ next, dist[next] });
}
}
}
}
int main() {
cin >> n >> m;
for (int i = 0; i < m; i++) {
int a, b, c;
cin >> a >> b >> c;
graph[a].push_back({ b, c });
graph[b].push_back({ a, c });
}
for (int i = 1; i <= n; i++) {
dist[i] = INF;
}
dijkstra(1);
cout << dist[n];
return 0;
}