-
[11779] 최소비용 구하기 2BOJ 2022. 2. 3. 16:57
https://www.acmicpc.net/problem/11779
11779번: 최소비용 구하기 2
첫째 줄에 도시의 개수 n(1≤n≤1,000)이 주어지고 둘째 줄에는 버스의 개수 m(1≤m≤100,000)이 주어진다. 그리고 셋째 줄부터 m+2줄까지 다음과 같은 버스의 정보가 주어진다. 먼저 처음에는 그 버스
www.acmicpc.net
<문제>
경로가 갱신될때마다 이전 노드를 저장한다면, e에서 s까지 역으로 경로를 복원할 수 있다.
물론, 이렇게 만들어진 경로는 도착->출발 순서이므로, 필요에 따라 reverse해주면 된다.
<소스코드>
#include <bits/stdc++.h> using namespace std; using ll = long long; const ll MAX_N = 100'000, INF = (ll)1e17; ll n, m, s, e, dst[MAX_N + 1], path[MAX_N + 1]; typedef struct { ll idx, cost; } state; vector<state> adj[MAX_N + 1]; void dijkstra(ll s) { auto cmp = [&](state& A, state& B) -> bool { return A.cost > B.cost; }; priority_queue<state, vector<state>, decltype(cmp)> q(cmp); q.push({s, 0}); fill(dst, dst + MAX_N + 1, INF); dst[s] = 0; while (!q.empty()) { state cur = q.top(); q.pop(); if (cur.cost > dst[cur.idx]) continue; for (auto& nxt : adj[cur.idx]) { if (dst[nxt.idx] > dst[cur.idx] + nxt.cost) { dst[nxt.idx] = dst[cur.idx] + nxt.cost; q.push({nxt.idx, dst[nxt.idx]}); path[nxt.idx] = cur.idx; } } } return; } void findPath(vector<ll>& ret) { ll cur = e; path[s] = -1; for (;; cur = path[cur]) { if (cur <= 0) break; ret.push_back(cur); } reverse(ret.begin(), ret.end()); return; } int main(void) { ios_base::sync_with_stdio(0); cin.tie(0); cin >> n >> m; ll i; for (i = 0; i < m; i++) { ll A, B, C; cin >> A >> B >> C; adj[A].push_back({B, C}); } cin >> s >> e; dijkstra(s); cout << dst[e] << '\n'; vector<ll> ret; findPath(ret); cout << ret.size() << '\n'; for (auto& i : ret) cout << i << ' '; return 0; }
'BOJ' 카테고리의 다른 글
[2210] 숫자판 점프 (0) 2022.02.05 [2776] 암기왕 (0) 2022.02.04 [18870] 좌표 압축 (0) 2022.02.03 [1238] 파티 (0) 2022.02.02 [12605] 단어순서 뒤집기 (0) 2022.01.29