Problem Statement
Cycle Finding
Implementation
void solve() {
ll n, m;
cin >> n >> m;
vector<vpll> v(n + 1);
rep(i, m) {
ll x, y, w;
cin >> x >> y >> w;
v[x].pb({ y, w });
}
FOR(i, 1, n) {
v[0].pb({ i, 0 });
}
n++;
vll d(n, inf), p(n, 0);
function < ll(ll) > bellman_ford = [&](ll node) {
ll st = -1;
d[node] = 0;
rep(i, n) {
st = -1;
rep(j, n) {
for (auto& child : v[j]) {
if (d[j] < inf && d[child.f] > d[j] + child.s) {
p[child.f] = j;
st = child.f;
d[child.f] = max(-inf, d[j] + child.s);
}
}
}
}
return st;
};
ll st = bellman_ford(0);
if (st == -1) {
cout << "NO\n";
return;
}
debug(st, p);
rep(i, n) st = p[st];
vll cycle;
for (ll i = st; ; i = p[i]) {
cycle.pb(i);
if (i == st && sz(cycle) > 1) break;
}
cout << "YES\n";
reverse(all(cycle));
rep(i, sz(cycle)) cout << cycle[i] << " ";
cout << "\n";
}