๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm ๐Ÿง‘๐Ÿปโ€๐Ÿ’ป/Note

[C++, ํ…œํ”Œ๋ฆฟ] ๋‹ค์ต์ŠคํŠธ๋ผ

by dkswnkk 2022. 5. 28.

๋‹ค์ต์ŠคํŠธ๋ผ

#include <iostream>
#include <queue>
#include <algorithm>
#define INF 1E9
using namespace std;
// ๋…ธ๋“œ์˜ ๊ฐœ์ˆ˜(V), ๊ฐ„์„ ์˜ ๊ฐœ์ˆ˜(E), ์‹œ์ž‘ ๋…ธ๋“œ ๋ฒˆํ˜ธ(K)
// ๋…ธ๋“œ์˜ ๊ฐœ์ˆ˜๋Š” ์ตœ๋Œ€ 20000๊ฐœ๋ผ๊ณ  ๊ฐ€์ •
int V, E, K;
// ๊ฐ ๋…ธ๋“œ์— ์—ฐ๊ฒฐ๋˜์–ด ์žˆ๋Š” ๋…ธ๋“œ์— ๋Œ€ํ•œ ์ •๋ณด๋ฅผ ๋‹ด๋Š” ๋ฐฐ์—ด
vector<pair<int,int>>graph[20001];
// ์ตœ๋‹จ ๊ฑฐ๋ฆฌ ํ…Œ์ด๋ธ” ๋งŒ๋“ค๊ธฐ
int d[20001];
void dijkstra(int start){
priority_queue<pair<int,int>,vector<pair<int,int>>, greater<pair<int,int>>>pq;
// ์‹œ์ž‘ ๋…ธ๋“œ๋กœ ๊ฐ€๊ธฐ ์œ„ํ•œ ์ตœ๋‹จ ๊ฒฝ๋กœ๋Š” 0์œผ๋กœ ์„ค์ •ํ•˜์—ฌ, ํ์— ์‚ฝ์ž…
pq.push({0, start});
d[start] = 0;
while(!pq.empty()){
int dist = pq.top().first; // ํ˜„์žฌ ๋…ธ๋“œ๊นŒ์ง€์˜ ๋น„์šฉ
int now = pq.top().second; // ํ˜„์žฌ ๋…ธ๋“œ
pq.pop();
// ํ˜„์žฌ ๋…ธ๋“œ๊ฐ€ ์ด๋ฏธ ์ฒ˜๋ฆฌ๋œ ์ ์ด ์žˆ๋Š” ๋…ธ๋“œ๋ผ๋ฉด ๋ฌด์‹œ
if(d[now]<dist) continue;
// ํ˜„์žฌ ๋…ธ๋“œ์™€ ์—ฐ๊ฒฐ๋œ ๋‹ค๋ฅธ ์ธ์ ‘ํ•œ ๋…ธ๋“œ๋“ค์„ ํ™•์ธ
for(auto neighbor: graph[now]){
int cost = dist + neighbor.second;
// ํ˜„์žฌ ๋…ธ๋“œ๋ฅผ ๊ฑฐ์ณ์„œ, ๋‹ค๋ฅธ ๋…ธ๋“œ๋กœ ์ด๋™ํ•˜๋Š” ๊ฑฐ๋ฆฌ๊ฐ€ ๋” ์งง์€ ๊ฒฝ์šฐ
if(cost<d[neighbor.first]){
d[neighbor.first] = cost;
pq.push({cost, neighbor.first});
}
}
}
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(0);
// ๋ชจ๋“  ๊ฐ„์„  ์ •๋ณด๋ฅผ ์ž…๋ ฅ๋ฐ›๊ธฐ
cin>>V>>E>>K;
for(int i=0; i<E; i++){
int a,b,cost; cin>>a>>b>>cost;
// a๋ฒˆ ๋…ธ๋“œ์—์„œ b๋ฒˆ ๋…ธ๋“œ๋กœ ๊ฐ€๋Š” ๋น„์šฉ์ด c๋ผ๋Š” ์˜๋ฏธ
graph[a].push_back({b,cost});
}
// ์ตœ๋‹จ ๊ฑฐ๋ฆฌ ํ…Œ์ด๋ธ”์„ ๋ชจ๋‘ ๋ฌดํ•œ์œผ๋กœ ์ดˆ๊ธฐํ™”
fill(d, d+20001, INF);
// ๋‹ค์ต์ŠคํŠธ๋ผ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์ˆ˜ํ–‰
dijkstra(K);
// ๋ชจ๋“  ๋…ธ๋“œ๋กœ ๊ฐ€๊ธฐ ์œ„ํ•œ ์ตœ๋‹จ ๊ฑฐ๋ฆฌ๋ฅผ ์ถœ๋ ฅ
for(int i=1; i<=V; i++){
if(i==K) cout<<0<<'\n';
else if(d[i]==INF) cout<<"INF"<<'\n';
else cout<<d[i]<<'\n';
}
}

GitHub

LinkedIn

GitHub

LinkedIn