Cycle detection

For any function ff that maps a finite set to itself, and for any initial value x0x_0 in the set, the sequence of values x0,x1=f(x0),x2=f(x1),,xk=f(xk1),x_0,\ x_1=f(x_0),\ x_2=f(x_1),\ \dots,\ x_k=f(x_{k-1}),\ \dots eventually repeats some values, i.e., there is some i0i \ge 0 and some j>ij > i such that f(xj)=f(xi)f(x_j) = f(x_i). Once this happens, the sequence continues by repeating the cycle from xix_i to xj1x_{j-1}.

For instance, the function that maps (0,1,2,3,4,5,6,7,8)(0,1,2,3,4,5,6,7,8) to (6,6,0,1,4,3,3,4,0)(6,6,0,1,4,3,3,4,0) generates the following sequence when x0=2x_{0} = 2:

206316316312 \enspace 0 \enspace 6 \enspace 3 \enspace 1 \enspace 6 \enspace 3 \enspace 1 \enspace 6 \enspace 3 \enspace 1 \enspace \dots

In this sequence, the beginning of the cycle (631)(6\ 3\ 1) is found after 2 steps. In this case, i=2i=2, j=5j=5, and the periodicity is ji=3j-i=3.

Given a function that maps the interval [0,n1][0, n-1] to itself, and several starting values x0x_0, compute the corresponding values of jij - i and ii.

Input

Input starts with the number of cases. Every such case begins with two integer numbers 1n1051 \le n \le 10^5 and 0k10n0 \le k \le 10n. Follow, in order, the nn images of the numbers in [0,n1][0, n-1]. Follow kk numbers: the x0x_0’s for which the result must be computed.

Output

For every case, print its number and kk lines each one with jij-i and ii.

Observation

Since some of the private cases are huge, a recursive program may exhaust the recursion stack.

Problem information

Author: Xavier Martínez

Generation: 2026-01-25T10:09:21.548Z

© Jutge.org, 2006–2026.
https://jutge.org