-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcyclefinding.cpp
More file actions
67 lines (59 loc) · 1.24 KB
/
cyclefinding.cpp
File metadata and controls
67 lines (59 loc) · 1.24 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
#include <bits/stdc++.h>
using namespace std;
#define ar array
#define ll long long
const int MAX_N = 1e5 + 1;
const ll MOD = 1e9 + 7;
const ll INF = 1e9;
int n, m, pre[MAX_N], vis[MAX_N];
vector<ar<int,2>> adj[MAX_N];
vector<ll> dist;
void solve() {
cin >> n >> m;
for (int i = 0; i < m; i++) {
int u, v, w; cin >> u >> v >> w;
adj[u].push_back({v, w});
}
dist.assign(n + 1, INF);
dist[1] = 0;
for (int k = 0; k < n - 1; k++) {
for (int u = 1; u <= n; u++) {
for (auto [v, w] : adj[u]) {
if (dist[v] > dist[u] + w) {
dist[v] = dist[u] + w;
pre[v] = u;
}
}
}
}
for (int u = 1; u <= n; u++) {
for (auto [v, w] : adj[u]) {
if (dist[v] > dist[u] + w) {
while (!vis[v]) {
vis[v] = 1;
v = pre[v];
}
vector<int> ans;
ans.push_back(v);
for (int k = pre[v]; k != v; k = pre[k]) ans.push_back(k);
ans.push_back(v);
reverse(ans.begin(), ans.end());
cout << "YES\n";
for (int x : ans) cout << x << " ";
cout << "\n";
return;
}
}
}
cout << "NO\n";
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
int tc = 1;
// cin >> tc;
for (int t = 1; t <= tc; t++) {
// cout << "Case #" << t << ": ";
solve();
}
}