Problem Statement
Round Trip II
Implementation
void solve() {
ll n, m;
cin >> n >> m;
vvll v(n);
rep(i, m) {
ll x, y;
cin >> x >> y;
--x, --y;
v[x].pb(y);
}
vll p(n, -1), col(n, 0);
function <bool(ll, ll)> dfs = [&](ll node, ll pr) {
col[node] = 1;
p[node] = pr;
for (auto& child : v[node]) {
if (col[child] == 0) {
if (dfs(child, node)) return 1;
}
else if (col[child] == 1) {
ll st = child, et = node;
vll cycle;
cycle.pb(st);
while (st ^ et) {
cycle.pb(et);
et = p[et];
}
cycle.pb(st);
reverse(all(cycle));
cout << sz(cycle) << "\n";
for (auto& x : cycle) cout << x + 1 << " ";
cout << "\n";
return 1;
}
}
col[node] = 2;
return 0;
};
rep(i, n) {
if (col[i] == 0) {
if (dfs(i, i)) {
return;
}
}
}
cout << "IMPOSSIBLE\n";
}