Graph Algorithms

Answer & solution
Answer: Climb from both endpoints in parallel until one reaches the other original endpoint; print the successful parent path and the added closing edge. (no official key was published)
In an undirected DFS tree, every non-tree edge joins an ancestor and a descendant. To see why, suppose an edge joined distinct DFS subtrees: while its first endpoint’s subtree was explored, the still-undiscovered other endpoint would be reached by that edge and placed in the same subtree, a contradiction. Thus the tree path between u and v is a single upward parent chain from the descendant. Which endpoint is deeper is not given, so climbing just one chosen endpoint can waste time or stick at the root.
Climb both parent chains in lockstep, saving both traversals, and stop as soon as one reaches the other original endpoint:
procedure PrintCycle(u,v);
begin
a:=u; b:=v; lenA:=1; lenB:=1;
pathA[1]:=u; pathB[1]:=v;
while (a<>v) and (b<>u) do begin
a:=P[a]; lenA:=lenA+1; pathA[lenA]:=a;
b:=P[b]; lenB:=lenB+1; pathB[lenB]:=b
end;
if a=v then begin
for k:=1 to lenA do write(pathA[k]);
write(u)
end else begin
for k:=1 to lenB do write(pathB[k]);
write(v)
end
end.Assume arrays can hold the tree height plus one and append/write are constant-time operations. Storage can instead be growable linked lists with constant-time append. Arrays need no initial clearing; only positions written above are read.
Let the ancestor–descendant distance be d. The descendant walk reaches the ancestor after exactly d rounds, even if the other walk has already reached the root and is repeating its self-parent. The algorithm performs at most 2d parent moves and prints d+1 distinct cycle vertices plus the repeated start: Θ(d+1), proportional to the cycle’s d+1 edges, with O(d+1) temporary storage. For example a parent chain 7→5→2 and new edge (2,7) prints 7,5,2,7.
No full-tree traversal, depth computation or global visited-array clearing is required. The argument assumes the usual simple undirected graph; a self-loop can be handled immediately by printing u,u. For an arbitrary spanning tree the ancestor property is false, so this algorithm is specifically justified by the DFS premise.