Algorithm
[๋ฐฑ์ค/C++] 1916. ์ต์๋น์ฉ ๊ตฌํ๊ธฐ
bba_dda
2021. 4. 14. 12:42
๋ฐ์ํ
๋ฌธ์
1916๋ฒ: ์ต์๋น์ฉ ๊ตฌํ๊ธฐ
์ฒซ์งธ ์ค์ ๋์์ ๊ฐ์ N(1 ≤ N ≤ 1,000)์ด ์ฃผ์ด์ง๊ณ ๋์งธ ์ค์๋ ๋ฒ์ค์ ๊ฐ์ M(1 ≤ M ≤ 100,000)์ด ์ฃผ์ด์ง๋ค. ๊ทธ๋ฆฌ๊ณ ์ ์งธ ์ค๋ถํฐ M+2์ค๊น์ง ๋ค์๊ณผ ๊ฐ์ ๋ฒ์ค์ ์ ๋ณด๊ฐ ์ฃผ์ด์ง๋ค. ๋จผ์ ์ฒ์์๋ ๊ทธ
www.acmicpc.net
ํ์ด
๋ค์ต์คํธ๋ผ ์๊ณ ๋ฆฌ์ฆ์ ์ด์ฉํด์ ํ์๋ค.
์๊ฐ ๋ณต์ก๋๋ฅผ ๋ฎ์ถ๊ธฐ ์ํด ํ์ ์ด์ฉํด ๊ตฌํํ๋ค.
์๊ฐ๋ณต์ก๋ : ๋ ธ๋๊ฐ V,๊ฐ์ ์ด E๊ฐ ์ผ ๋, O(E*logV)
๋ฐฑ์ง ์ํ์์ ๊ตฌํํ๋ ค๋ ์๊ฐ์ด ๋์ง ์์์, ์ ๋ฒ์ ๊ตฌํํด๋๋ ์ฝ๋๋ฅผ ์ถฉ๋ถํ ์์งํ ํ์ ๊ตฌํํด๋ณด์๋ค.
์ฝ๋
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
#define INF 987654321
vector<pair<int, int>> adjs[1001];
int min_dist[1001];
void Dijkstra(int start) {
priority_queue<pair<int, int>> pq;
pq.push(make_pair(0, start));
min_dist[start] = 0; //////
while (!pq.empty()) {
int cost = -pq.top().first;
int cur = pq.top().second;
pq.pop();/////
if (min_dist[cur] < cost) continue;
for (int i = 0;i < adjs[cur].size();i++) {
int there = adjs[cur][i].first;
int new_cost = cost + adjs[cur][i].second;
if (min_dist[there] > new_cost) {
min_dist[there] = new_cost;
pq.push(make_pair(-new_cost, there));
}
}
}
}
int main(void) {
// ์
์ถ๋ ฅ ์๊ฐ ๋จ์ถ์ฉ
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int n, m, a, b;
cin >> n >> m;
for (int i = 0;i < m;i++) {
int start, end, cost;
cin >> start >> end >> cost;
adjs[start].push_back(make_pair(end, cost));
}
cin >> a >> b;
fill(&min_dist[0], &min_dist[1002], INF);
Dijkstra(a);
cout << min_dist[b] << endl;
return 0;
}
๊ฒฐ๊ณผ
๋ฐ์ํ