|
| 1 | +#include <bits/stdc++.h> |
| 2 | +#include <ext/rope> |
| 3 | +using namespace std; |
| 4 | +using namespace __gnu_cxx; |
| 5 | + |
| 6 | +using ld = long double; |
| 7 | +using llint = long long; |
| 8 | +using ullint = unsigned long long; |
| 9 | +using pii = pair <int,int>; |
| 10 | +using pcc = pair <char,char>; |
| 11 | +using pss = pair <string,string>; |
| 12 | +using vi = vector <int>; |
| 13 | +using vb = vector <bool>; |
| 14 | +using vii = vi::iterator; |
| 15 | + |
| 16 | +#define INF (1<<30) |
| 17 | +#define MOD 1000000007 |
| 18 | +#define mp make_pair |
| 19 | +#define mt make_tuple |
| 20 | +#define all(c) c.begin(), c.end() |
| 21 | +#define ms(name,val) memset(name, val, sizeof name) |
| 22 | +#define np nullptr |
| 23 | + |
| 24 | + |
| 25 | +int main() |
| 26 | +{ |
| 27 | + ios_base::sync_with_stdio(0); |
| 28 | + //cin.tie(0); |
| 29 | + |
| 30 | + int n, m, s; |
| 31 | + cin >> n >> m >> s; |
| 32 | + vector <vector <pii>> g(n); |
| 33 | + |
| 34 | + for (int t1 = 0; t1 < m; ++t1) |
| 35 | + { |
| 36 | + int a, b, c; |
| 37 | + cin >> a >> b >> c; |
| 38 | + g[a].push_back({b,c}); |
| 39 | + g[b].push_back({a,c}); |
| 40 | + } |
| 41 | + |
| 42 | + set <pii> S; // dist, node |
| 43 | + S.insert({0, s}); |
| 44 | + |
| 45 | + for (int t1 = 0; t1 < n; ++t1) |
| 46 | + if (t1 != s) S.insert({INF, t1}); |
| 47 | + |
| 48 | + vb vis(n, 0); |
| 49 | + vi p(n, -1), dist(n, INF); |
| 50 | + dist[s] = 0; |
| 51 | + |
| 52 | + for (int t1 = 0; t1 < n-1; ++t1) |
| 53 | + { |
| 54 | + int node = S.begin()->second; |
| 55 | + int ndist = S.begin()->first; |
| 56 | + S.erase(S.begin()); |
| 57 | + vis[node] = 1; |
| 58 | + |
| 59 | + for (int t2 = 0; t2 < g[node].size(); ++t2) |
| 60 | + { |
| 61 | + int x = g[node][t2].first; |
| 62 | + int y = g[node][t2].second; |
| 63 | + if (vis[x]) continue; |
| 64 | + |
| 65 | + if (dist[x] > ndist+y) |
| 66 | + { |
| 67 | + S.erase({dist[x], x}); |
| 68 | + dist[x] = ndist+y; |
| 69 | + S.insert({dist[x], x}); |
| 70 | + p[x] = node; // for finding the path |
| 71 | + } |
| 72 | + } |
| 73 | + } |
| 74 | + |
| 75 | + cout << '\n'; |
| 76 | + |
| 77 | + for (int t1 = 0; t1 < n; ++t1) |
| 78 | + { |
| 79 | + cout << dist[t1] << " -> "; |
| 80 | + int node = t1; |
| 81 | + |
| 82 | + while (node != -1) |
| 83 | + { |
| 84 | + cout << node << ' '; |
| 85 | + node = p[node]; |
| 86 | + } |
| 87 | + |
| 88 | + cout << '\n'; |
| 89 | + } |
| 90 | + |
| 91 | + |
| 92 | + return 0; |
| 93 | +} |
0 commit comments