|
| 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 n, m, src; |
| 26 | +vi dist; |
| 27 | +vector <tuple <int,int,int>> g; |
| 28 | + |
| 29 | +void bellmanFord() |
| 30 | +{ |
| 31 | + dist.assign(n, INF); |
| 32 | + dist[src] = 0; |
| 33 | + |
| 34 | + for (int t1 = 1; t1 < n; ++t1) |
| 35 | + { |
| 36 | + // use a bool variable to optimize the second for loop |
| 37 | + |
| 38 | + for (int t2 = 0; t2 < m; ++t2) |
| 39 | + { |
| 40 | + int a = get<0>(g[t2]); |
| 41 | + int b = get<1>(g[t2]); |
| 42 | + int c = get<2>(g[t2]); |
| 43 | + dist[b] = min(dist[b], dist[a]+c); |
| 44 | + // if no improvements have been made, exit from these 2 for loops |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + for (int t1 = 0; t1 < m; ++t1) |
| 49 | + { |
| 50 | + int a = get<0>(g[t1]); |
| 51 | + int b = get<1>(g[t1]); |
| 52 | + int c = get<2>(g[t1]); |
| 53 | + |
| 54 | + if (dist[b] > dist[a]+c) |
| 55 | + { |
| 56 | + cout << "Graph contains a negative cycle!\n"; |
| 57 | + return; |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + for (int t1 = 0; t1 < n; ++t1) |
| 62 | + cout << dist[t1] << ' '; |
| 63 | + |
| 64 | + cout << '\n'; |
| 65 | +} |
| 66 | + |
| 67 | +int main() |
| 68 | +{ |
| 69 | + ios_base::sync_with_stdio(0); |
| 70 | + //cin.tie(0); |
| 71 | + |
| 72 | + cin >> n >> m >> src; |
| 73 | + g.resize(m); |
| 74 | + |
| 75 | + for (int t1 = 0; t1 < m; ++t1) |
| 76 | + { |
| 77 | + int a, b, c; |
| 78 | + cin >> a >> b >> c; |
| 79 | + g[t1] = {a,b,c}; |
| 80 | + } |
| 81 | + |
| 82 | + bellmanFord(); |
| 83 | + |
| 84 | + |
| 85 | + |
| 86 | + return 0; |
| 87 | +} |
0 commit comments