-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbee1391.cpp
More file actions
86 lines (68 loc) · 1.44 KB
/
Copy pathbee1391.cpp
File metadata and controls
86 lines (68 loc) · 1.44 KB
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/*
* Contest : Beecrowd
* Problem : 1391 - Quase menor caminho
* Link : https://judge.beecrowd.com/pt/problems/view/1391
* Time : O((N + M) logN)
*/
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define fastio ios::sync_with_stdio(0); cin.tie(0);
const int INF = 1e9;
vector<vector<pair<int,int>>> graph, rev;
set<pair<int,int>> used;
vector<int> dist;
int n, m, s, d;
int dijkstra(int s) {
dist.assign(n, INF);
priority_queue<pair<int, int>> pq;
dist[s] = 0;
pq.push({0, s});
while (!pq.empty()) {
auto [du, u] = pq.top();
pq.pop();
if (-du > dist[u]) continue;
for (auto& [v,w] : graph[u]) {
if (used.count({u,v})) continue;
if (dist[u]+w < dist[v]) {
dist[v] = dist[u]+w;
pq.emplace(-dist[v], v);
}
}
}
return dist[d];
}
void bfs(int src) {
queue<int> q;
q.push(src);
while (!q.empty()) {
int u = q.front();
q.pop();
for (auto& [v,w] : rev[u]) {
if (dist[v]+w == dist[u]) {
q.push(v);
used.emplace(v, u);
}
}
}
}
int main() {
fastio
while (cin >> n >> m, n) {
graph.assign(n, {});
rev.assign(n, {});
cin >> s >> d;
int u, v, p;
while (m--) {
cin >> u >> v >> p;
graph[u].emplace_back(v,p);
rev[v].emplace_back(u,p);
}
int sp = dijkstra(s);
bfs(d);
sp = dijkstra(s);
cout << (sp!=INF? sp : -1) << '\n';
used.clear();
}
return 0;
}