반응형

www.acmicpc.net/problem/1504

 

1504번: 특정한 최단 경로

첫째 줄에 정점의 개수 N과 간선의 개수 E가 주어진다. (2 ≤ N ≤ 800, 0 ≤ E ≤ 200,000) 둘째 줄부터 E개의 줄에 걸쳐서 세 개의 정수 a, b, c가 주어지는데, a번 정점에서 b번 정점까지 양방향 길이 존

www.acmicpc.net

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
#include <cstring>
#define rep(i,n) for(int i=1;i<=n;i++)
#define pii pair<intint>
#define MAX 200000000
using namespace std;
int n, e, a, b, c, v1, v2, ans1, ans2, dist[801];
struct cmp {
    bool operator()(const pii& a, const pii& b) {
        return a.second > b.second;
    }
};
vector<vector<pii> > vec;
priority_queue<pii, vector<pii>, cmp> pq;
void dijk(int start) {
    fill(dist, dist + n + 1, MAX);
    pq.push({ start, 0 });
    dist[start] = 0;
    while (!pq.empty()) {
        int now_v = pq.top().first;
        int now_w = pq.top().second;
        pq.pop();
        if (dist[now_v] < now_w) continue;
        for (pii next : vec[now_v]) {
            int next_v = next.first;
            int next_w = next.second + now_w;
            if (dist[next_v] > next_w) {
                dist[next_v] = next_w;
                pq.push({ next_v, next_w });
            }
        }
    }
}
int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cin >> n >> e;
    vec.resize(n + 1);
    rep(i, e) {
        cin >> a >> b >> c;
        vec[a].push_back({ b,c });
        vec[b].push_back({ a,c });
    }
    cin >> v1 >> v2;
    bool poss1 = true, poss2 = true;
    dijk(1);
    ans1 += dist[v1];
    ans2 += dist[v2];
 
    dijk(v1);
    ans1 += dist[v2];
    ans2 += dist[n];
 
    dijk(v2);
    ans1 += dist[n];
    ans2 += dist[v1];
    int ans = min(ans1, ans2);
    cout << (ans >= MAX ? -1 : ans);
        
}
cs
반응형

'백준 > 다익스트라' 카테고리의 다른 글

백준 1238 [복습 필수]  (0) 2021.02.19
백준 1261 [복습 필수]  (0) 2021.02.19
백준 1753 [복습 필수]  (0) 2021.02.19

+ Recent posts