-
[1504] 특정한 최단 경로BOJ 2022. 6. 21. 12:36
https://www.acmicpc.net/problem/1504
1504번: 특정한 최단 경로
첫째 줄에 정점의 개수 N과 간선의 개수 E가 주어진다. (2 ≤ N ≤ 800, 0 ≤ E ≤ 200,000) 둘째 줄부터 E개의 줄에 걸쳐서 세 개의 정수 a, b, c가 주어지는데, a번 정점에서 b번 정점까지 양방향 길이 존
www.acmicpc.net
방문하는 두 정점이 x, y라고 하면,
1 - x - y - n
1 - y - x - n위 두 가지 경우만 체크하면 된다.
x나 y가 1, n인 경우도 나올 수 있지만, 예외처리를 할 필요는 없다.
입력이 연결그래프인지를 먼저 판별하면 -1을 출력해야 하는 경우를 배제하고 시작할수도 있겠다.
#include <bits/stdc++.h>using namespace std;#ifdef ONLINE_JUDGEconstexpr bool local = false;#elseconstexpr bool local = true;#endifusing ll = long long;using pi = pair<ll, ll>;typedef struct {ll idx, cost;} state;constexpr ll MAX_N = 100000, INF = (ll)1e17;ll n, m, s, e, dst[MAX_N + 1];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]});}}}return;}int main(void) {if (!local) 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});adj[B].push_back({A, C});}ll ans = INF, x, y, cur = 0;cin >> x >> y;for (i = 0; i < 2; i++, swap(x, y), cur = 0) {dijkstra(1), cur += dst[x];if (dst[x] == INF or dst[y] == INF or dst[n] == INF) continue;dijkstra(x), cur += dst[y];dijkstra(y), cur += dst[n];ans = min(cur, ans);}if (ans == INF) {cout << "-1";return 0;}cout << ans;return 0;}
'BOJ' 카테고리의 다른 글
[14907] 프로젝트 스케줄링 (0) 2022.07.04 [2585] 경비행기 (0) 2022.06.23 [16168] 퍼레이드 (0) 2022.05.22 [1199] 오일러 회로 (0) 2022.05.22 [18005] Even or Odd? (0) 2022.05.20