๋ค์ต์คํธ๋ผ
#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'; } }
'Algorithm ๐ง๐ปโ๐ป > Note' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
๋นํธ๋ง์คํฌ(BitMask) (0) | 2022.09.16 |
---|---|
[C++, ํ ํ๋ฆฟ] ์ ๋์จ ํ์ธ๋ (0) | 2022.09.02 |
[C++, ํ ํ๋ฆฟ] map find index (0) | 2022.08.23 |
[C++, ํ ํ๋ฆฟ] ํ๋ก์ด๋-์์ฌ (0) | 2022.05.13 |
[C++, ์ ์ฉํ ๋ฌธ๋ฒ] upper_bound, lower_bound (0) | 2022.05.11 |
[C++, ํ ํ๋ฆฟ] ์์ ๊ตฌํ๊ธฐ(์๋ผํ ์คํธ๋ค์ค์ ์ฒด) (0) | 2022.04.11 |
๋๊ธ