https://www.acmicpc.net/problem/5972
5972번: 택배 배송
농부 현서는 농부 찬홍이에게 택배를 배달해줘야 합니다. 그리고 지금, 갈 준비를 하고 있습니다. 평화롭게 가려면 가는 길에 만나는 모든 소들에게 맛있는 여물을 줘야 합니다. 물론 현서는
www.acmicpc.net
코드
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
int N,M;
int dp[50001];
vector<pair<int, int> > ways[50001];
void input(){
int a,b,c;
cin>>N>>M;
for(int i=0;i<M;++i){
cin>>a>>b>>c;
ways[a].push_back({b,c});
ways[b].push_back({a,c});
}
}
int dijkstra(){
priority_queue<pair<int, int> > pq;
pq.push({0,1});
dp[1] = 0;
while(!pq.empty()){
int cost = -pq.top().first;
int node = pq.top().second;
pq.pop();
if(dp[node] < cost)
continue;
for(int i=0;i<ways[node].size();++i){
int next = ways[node][i].first;
int ncost = ways[node][i].second + cost;
if(dp[next] <= ncost)
continue;
pq.push({-ncost,next});
dp[next] = ncost;
}
}
return dp[N];
}
void solution(){
fill(&dp[0], &dp[50001], 987'654'321);
cout<<dijkstra()<<'\n';
}
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
input();
solution();
return 0;
}

728x90
'알고리즘 > 백준 문제' 카테고리의 다른 글
| 7682 - 틱택토 (0) | 2023.08.04 |
|---|---|
| 2467 - 용액 (0) | 2023.08.02 |
| 1943 - 동전 분배 (0) | 2023.07.25 |
| 14719 - 빗물 (0) | 2023.07.25 |
| 20437 - 문자열 게임 2 (0) | 2023.07.24 |
댓글