1#include <bits/stdc++.h>2usingnamespace std;34voidfloyd_cycle(int x, constvector<int>&succ, vector<int>&ans){5int a = succ[x], b = succ[succ[x]];6// meet inside the cycle, but bail if we hit a known node7while (a != b) {8if (ans[a] || ans[b]) break; // <<< early exit if chain already solved9 a = succ[a]; b = succ[succ[b]];10 }11// Only do cycle work if we actually found a *new* cycle12if (a == b && ans[a] ==0) { // <<< skip if cycle already labeled13// find cycle entry14 a = x;15while (a != b) { a = succ[a]; b = succ[b]; }16int entry = a;1718// find cycle length19int len =1, nxt = succ[entry];20while (nxt != entry) { nxt = succ[nxt]; len++; }2122// fill cycle nodes23int v = entry;24do { ans[v] = len; v = succ[v]; } while (v != entry);25 }26// fill tail toward the first known node/cycle27vector<int> path;28int v = x;29while (ans[v] ==0) { path.push_back(v); v = succ[v]; }30for (int i = (int)path.size() -1; i >=0; --i)31 ans[path[i]] = ans[succ[path[i]]] +1;32}33intmain(){34 ios::sync_with_stdio(0);35 cin.tie(0);36int n; cin >> n;37vector<int>succ(n +1), ans(n +1);38for(int i =1; i <= n; i++){39 cin >> succ[i];40 }41for(int i =1; i <= n; i++){42if(ans[i] ==0) floyd_cycle(i, succ, ans);43 }44for(int i =1; i <= n; i++){45 cout << ans[i] << (i == n ?"\n":" ");46 }47return0;48}
☕
Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.
Python records executed lines and locals automatically. For selected values in any language, add // @trace i, total on its own valid line; Python uses # @trace i, total.
StatusReady
Output
No run yet.
Diagnostics
No diagnostics yet.
Each run is isolated and has strict limits. Passing one test does not guarantee the judge will accept the solution.