-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcycle_finding.cpp
69 lines (54 loc) · 1.43 KB
/
cycle_finding.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
67
68
69
#include <bits/stdc++.h>
using namespace std;
#define llong long long int
const llong INF = 1e18 + 5;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n, m;
cin >> n >> m;
vector<tuple<int, int, int>> edges(m);
for (int i = 0; i < m; i++) {
int a, b, c;
cin >> a >> b >> c;
edges[i] = make_tuple(a - 1, b - 1, c);
}
vector<int> prev(n, -1);
vector<llong> dist(n, INF);
dist[0] = 0;
for (int i = 1; i < n; i++)
for (auto [u, v, w]: edges)
if (dist[u] + w < dist[v]) {
prev[v] = u;
dist[v] = dist[u] + w;
}
int end = -1;
for (auto [u, v, w]: edges)
if (dist[u] + w < dist[v]) {
end = v;
prev[v] = u;
dist[v] = dist[u] + w;
}
if (end == -1) cout << "NO\n";
else {
int v = end;
vector<int> ans;
vector<bool> seen(n, false);
while (!seen[v]) {
seen[v] = true;
ans.push_back(v + 1);
v = prev[v];
assert(v != -1);
}
cout << "YES\n";
cout << (v + 1);
seen.assign(n, false);
seen[v] = true;
int idx = (int) ans.size() - 1;
while (idx >= 0 && !seen[ans[idx] - 1]) {
cout << " " << ans[idx];
seen[ans[idx--] - 1] = true;
}
cout << " " << ans[idx] << "\n";
}
}