-
Notifications
You must be signed in to change notification settings - Fork 0
/
P1504.cpp
66 lines (48 loc) · 1.31 KB
/
P1504.cpp
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
64
65
66
#include <iostream>
#include <vector>
#include <queue>
#define INF 987654321
using namespace std;
typedef pair<int, int> pii;
vector<pii> graph[801];
int N, E;
int A, B;
int dijk(int start, int v) {
vector<int> distance(N + 1, INF);
priority_queue<pii> pq;
distance[start] = 0;
pq.push({0, start});
while (!pq.empty()) {
int cost = -pq.top().first;
int here = pq.top().second;
pq.pop();
if (distance[here] < cost) continue;
for (int i = 0; i < graph[here].size(); i++) {
int next = graph[here][i].first;
int next_cost = cost + graph[here][i].second;
if (distance[next] > next_cost) {
distance[next] = next_cost;
pq.push({-next_cost, next});
}
}
}
return distance[v];
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> N >> E;
for (int i = 0; i < E; i++) {
int a, b, c;
cin >> a >> b >> c;
graph[a].emplace_back(b, c);
graph[b].emplace_back(a, c);
}
cin >> A >> B;
int a = dijk(1, A) + dijk(A, B) + dijk(B, N);
int b = dijk(1, B) + dijk(B, A) + dijk(A, N);
if (a >= INF || b >= INF || a < 0 || b < 0) cout << "-1";
else cout << min(a, b);
return 0;
}