problems / 129

Where the Chain Loops Back

medium linked-list two-pointers 1000 ms · 32 MB

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.

Example 1

Input

5 4
1 3
2 5
3 5
4 2
5 1

Output

5 3

Example 2

Input

4 2
4 4
1 0
3 1
2 3

Output

NO CYCLE

Example 3

Input

1 1
1 1

Output

1 1

Hints · reveal one at a time if you're stuck

Hint 1

Each node has exactly one successor, so the walk from the head is fully determined. With a tight memory limit you cannot record every visited node, so think about how you can detect a repeat from the walk itself.

Hint 2

Walk two pointers from the head at different speeds to detect a cycle, then restart one pointer at the head and step both one at a time to find the entry. Finally walk once around the loop to measure its length. Each phase uses only a few integers.

report an issue Prefer your own editor? sooks prep 129 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.