Where the Chain Loops Back
A singly linked list is stored as n records. Every node has a distinct id from 1 to n. A
node's record gives its id and next, the id of the node it points to, where next = 0 means it
points to nothing. The records come in arbitrary order, not in list order.
Start at the head node h and keep following next. Either the walk reaches 0 and ends, or it
goes on forever, which means it has fallen into a cycle. In that case, find the first node of
the walk that lies on the cycle (the node where the chain loops back) and the length of the
cycle, which is the number of distinct nodes on it.
Nodes that can't be reached from the head may point anywhere. They don't affect the answer.
The memory limit is small. The intended solution stores the input plus a constant amount of extra data.
Input
The first line contains two integers n and h (1 ≤ n ≤ 5·10^5, 1 ≤ h ≤ n): the number of
nodes and the id of the head.
Each of the next n lines contains two integers id and next (1 ≤ id ≤ n,
0 ≤ next ≤ n). Every id from 1 to n appears in exactly one record. A node may point to
itself, and several nodes may point to the same node.
Output
If the walk from the head reaches 0, print NO CYCLE.
Otherwise print two integers separated by a space: the id of the first node of the walk that lies on the cycle, and the length of the cycle.
Notes
In the first example the walk is 4 → 2 → 5 → 1 → 3 → 5 → .... Node 5 is the first node on the
cycle 5 → 1 → 3 → 5, which has length 3.
In the second example the walk is 2 → 3 → 1, and node 1 points to 0. Node 4 points to
itself, but the head can't reach it, so there is no cycle.
In the third example the only node points to itself, so the cycle starts at the head and has length
1.