Distance queries in functional graphs require understanding the tail-cycle structure. Precompute cycle membership and distances to avoid simulation. This preprocessing is what makes it work. Case analysis is unavoidable. Each combination of tail/cycle positions needs different logic.
Handle all cases explicitly. Missing a case leads to wrong answers. Binary lifting helps with jumping to the cycle quickly. Combined with cycle indices, you answer queries in time. This is fast enough for competitive programming constraints.