#P5903. 【模板】树上 K 级祖先

【模板】树上 K 级祖先

Description

Given a rooted tree with nn nodes.

There are qq queries. In the ii-th query, xix_i and kik_i are given. You need to find the kik_i-th ancestor of node xix_i, and denote the answer as ansians_i. In particular, ans0=0ans_0 = 0.

The queries in this problem are generated within the program.

A random seed ss and a random function get(x)\operatorname{get}(x) are given:

#define ui unsigned int
ui s;

inline ui get(ui x) {
	x ^= x << 13;
	x ^= x >> 17;
	x ^= x << 5;
	return s = x; 
}

You need to generate the queries in order.

Let did_i be the depth of node ii, where the root has depth 11.

For the ii-th query, $x_i = ((\operatorname{get}(s) \operatorname{xor} ans_{i-1}) \bmod n) + 1$, and $k_i = (\operatorname{get}(s) \operatorname{xor} ans_{i-1}) \bmod d_{x_i}$.

Input Format

The first line contains three integers n,q,sn, q, s.

The second line contains nn integers f1nf_{1\dots n}, where fif_i is the parent of ii. In particular, if fi=0f_i = 0, then ii is the root.

Output Format

Output one integer per line, representing xori=1qi×ansi\operatorname{xor}_{i=1}^q i \times ans_i.

6 3 7
5 5 2 2 0 3

1

Hint

[Sample Explanation]

x1=4x_1 = 4, k1=1k_1 = 1, ans1=2ans_1 = 2.
x2=6x_2 = 6, k2=3k_2 = 3, ans2=5ans_2 = 5.
x3=3x_3 = 3, k3=0k_3 = 0, ans3=3ans_3 = 3.
Therefore, the output is 11.


For 20%20\% of the testdata, n,q103n, q \le 10^3.

For 50%50\% of the testdata, n,q105n, q \le 10^5.

For 100%100\% of the testdata, 2n5×1052 \le n \le 5 \times 10^5, 1q5×1061 \le q \le 5 \times 10^6, 1s<2321 \le s < 2^{32}.

Translated by ChatGPT 5