#P5557. 旅行

旅行

Description

Walking through the mortal world, charine is a traveler. Stepping into the noise of cities, he begins his journey from city to city.

There is a group of cities with nn cities, and any two cities are reachable from each other. With the rapid development of modern transportation, travel time has been greatly reduced, so distance no longer seems that important:

In this city group, roads no longer have different lengths. Because travel time keeps shrinking, every road can be regarded as having the same length, measured as one unit, which can be seen as 11 zm.

However, because the city group is huge and charine still has things tying him down, he cannot travel forever in this vast city group. This makes him very upset, so he decides to spend as little time as possible to visit the entire city group.

Specifically, charine will not waste time staying in any city. Every city he visits will be remembered in a very short time.

charine does not walk fast, which means he can only walk 11 zm in one unit of time.

This makes him even more eager to find a way to travel to more cities.

To remove the hesitation time at every intersection, charine wisely planned his trip in advance. For the exits leaving city ii, charine defines a “passage” aia_i for this city. He trusts his plan and will definitely follow the passage forward. After visiting city ii, he will set his next target city to be aia_i.

After finishing these preparations, he can no longer find any way to further shorten the time, so he starts executing his travel plan.

charine has mm seasons when he has a chance to travel. For the ii-th season, charine will start from SiS_i. He tells you that he will prepare tt units of time for traveling.

To see him in time, you need to know: after tt units of time, which city will charine appear in?

Note the difference between the definitions of “road” and “passage”.

Input Format

The first line contains a positive integer nn, the number of cities.

The second line contains nn integers. The ii-th integer is aia_i.

Next is an integer mm, indicating mm seasons.

Lines 44 to m+3m+3 each describe one trip. Each line contains three integers Si,t1,t2S_i, t_1, t_2 as described above, where t=t1t2t=t_1^{t_2}.

Output Format

For each season, output one line containing the answer.

6
2 3 4 5 6 1
3
1 2 2
2 7 1
6 1 1
5
3
1

Hint

Sample explanation:

Start from 11 and walk 222^{2} steps to reach 55 (123451-2-3-4-5).

Start from 22 and walk 717^{1} steps to reach 33 (234561232-3-4-5-6-1-2-3).

Start from 66 and walk 111^{1} step to reach 11 (616-1).

For 10%10\% of the testdata, n100n\leq 100, m300m\leq 300, t1100t_1\leq 100.

For 50%50\% of the testdata, n3000n\leq 3000, m3000m\leq 3000, t13000t_1\leq 3000, t2=1t_2=1.

For 70%70\% of the testdata, n3000n\leq 3000, m3000m\leq 3000.

For 100%100\% of the testdata, n400000n\leq 400000, m300000m\leq 300000, t1109t_1\leq 10^{9}, t2109t_2\leq 10^9.

Translated by ChatGPT 5