문제 링크: https://www.acmicpc.net/problem/1753
문제 이름에서도 볼 수 있듯이 최단경로 문제입니다. 정말 기본형중의 기본형입니다.
벨만포드 알고리즘이나 다익스트라 알고리즘을 사용하면 됩니다.
공부할 겸 다익스트라 알고리즘 코드를 안보고 구현해봤는데 역시 실수가 있었습니다. 역시 갈길이 멉니다.
#pragma GCC optimize ("Ofast")
#define _CRT_SECURE_NO_WARNINGS
#define _SILENCE_CXX17_C_HEADER_DEPRECATION_WARNING
#include <bits/stdc++.h>
using namespace std;
const int INF = 987654321;
vector<pair<int, int>> adj[20000]; // idx, cost
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
//freopen("output.txt", "w", stdout);
#endif
ios_base::sync_with_stdio(false);
cin.tie(nullptr), cout.tie(nullptr);
int v, e, k;
cin >> v >> e >> k;
--k;
for (int i = 0; i < e; ++i) {
int u, v, w;
cin >> u >> v >> w;
--u, --v;
adj[u].emplace_back(v, w);
}
priority_queue<pair<int, int>> pq; // cost(-), idx
vector<int> dist(v, INF);
dist[k] = 0;
pq.emplace(0, k);
while (!pq.empty()) {
auto [cost, idx] = pq.top();
pq.pop();
cost = -cost;
if (dist[idx] < cost) continue;
for (auto& edge : adj[idx]) {
auto next = edge.first;
auto nextDist = cost + edge.second;
if (dist[next] > nextDist) {
dist[next] = nextDist;
pq.emplace(-nextDist, next);
}
}
}
for (auto& d : dist) {
if (d == INF)
cout << "INF\n";
else
cout << d << '\n';
}
return 0;
}
다익스트라 알고리즘으로 푼 코드입니다
반응형
'Online Judge > 백준' 카테고리의 다른 글
[백준][C++] 18234: 당근 훔쳐 먹기 (0) | 2020.07.20 |
---|---|
[백준][C++] 14247: 나무 자르기 (0) | 2020.07.20 |
[백준][C++] 1269: 대칭 차집합 (0) | 2020.07.19 |
[백준][C++] 17370: 육각형 우리 속의 개미 (0) | 2020.07.19 |
[백준][C++] 18917: 수열과 쿼리 38 (0) | 2020.07.18 |