-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbellmanford.cpp
More file actions
103 lines (87 loc) · 1.68 KB
/
bellmanford.cpp
File metadata and controls
103 lines (87 loc) · 1.68 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#include<bits/stdc++.h>
using namespace std;
#define PI 3.1415926535897932384626433832795
#define MOD 1000000007
#define pb push_back
#define rep(i,a,b) for(int i=a;i<b;i++)
#define vl vector<ll>
#define vi vector<int>
#define lb lower_bound
#define ub upper_bound
// vector<vector<int>> vec( n , vector<int> (m, 0));
// priority_queue<pi, vector<pi>, greater<pi>>q;
typedef int64_t ll;
#define pi pair<ll, int>
void bellmanford()
{
int n , m;
cin >> n >> m;
vector<pair<pair<int, int>, ll>>adj;
for (int i = 0; i < m; ++i)
{
int c1, c2, w;
cin >> c1 >> c2 >> w;
adj.pb({{c1, c2}, w});
}
vector<ll>dist(n + 1, 1e18);
vector<int>parent(n + 1, 0);
dist[1] = 0;
int s;
// bellmanford
for (int i = 0; i < n; i++)
{
s = -1;
for (auto it : adj)
{
int c1 = it.first.first;
int c2 = it.first.second;
ll d = it.second;
if (dist[c2] > dist[c1] + d)
{
parent[c2] = c1;
dist[c2] = dist[c1] + d;
s = c2;
}
}
}
if (s == -1)
{
// negative cycle not detected
cout << "NO" << endl;
return;
}
cout << "YES" << endl;
// backtracking path
for (int i = 0; i < n; i++)
{
s = parent[s];
}
int start = s;
cout << s << " ";
s = parent[s];
vector<int>path;
while (s != start)
{
// cout << s << " ";
path.pb(s);
s = parent[s];
}
reverse(path.begin(), path.end());
for (auto it : path)
{
cout << it << " ";
}
cout << start << endl;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
#ifndef ONLINE_JUDGE
freopen("input.in", "r", stdin);
freopen("output.out", "w", stdout);
#endif
// int t;
bellmanford();
return 0;
}