Under construction

Still being built. Things may change

Infinite Adventure

Time limit2sMemory limit1024 MB

Summary
Given portals whose cycle times are powers of 2, find the city reached after Delta portal hops from city v starting on day t.
Level

Medium7 of 10

Topics
Dynamic programming, Math
Solved
No attempts yet

Problem

Bessie is planning an infinite adventure in a land with NN (1≤N≤1051\leq N\leq 10^5) cities. Each city ii has a portal and a cycling time TiT_i. Every TiT_i is a power of 22, and T1+⋯+TN≤105T_1+\cdots+T_N\leq 10^5. If you enter city ii's portal on day tt, you instantly exit in city ci, t mod Tic_{i,\, t \bmod T_i}. Bessie has QQ (1≤Q≤5⋅1041\leq Q\leq 5\cdot 10^4) plans, each a tuple (v,t,Δ)(v, t, \Delta). In each plan she starts in city vv on day tt, then repeats the following Δ\Delta times: she follows the portal in her current city, then waits one day. For each plan, find the city where she ends up.

Input

The first line contains two integers NN and QQ, separated by a space. The second line contains T1,T2,…,TNT_1, T_2, \ldots, T_N, separated by spaces (1≤Ti1\leq T_i, each TiT_i is a power of 22, and T1+⋯+TN≤105T_1+\cdots+T_N\leq 10^5). For i=1,2,…,Ni=1,2,\ldots,N, line i+2i+2 contains ci,0,…,ci,Ti−1c_{i,0}, \ldots, c_{i,T_i-1}, separated by spaces (1≤ci,t≤N1\leq c_{i,t}\leq N). For j=1,2,…,Qj=1,2,\ldots,Q, line j+N+2j+N+2 contains three positive integers vj,tj,Δjv_j, t_j, \Delta_j separated by spaces (1≤vj≤N1\leq v_j\leq N, 1≤tj≤10181\leq t_j\leq 10^{18}, 1≤Δj≤10181\leq \Delta_j\leq 10^{18}).

Output

Print QQ lines. The jjth line is the answer to the jjth plan, the city where Bessie ends up.

Examples2

  1. Example 1

    Input
    5 4
    1 2 1 2 8
    2
    3 4
    4
    2 3
    5 5 5 5 5 1 5 5
    2 4 3
    3 3 6
    5 3 2
    5 3 7
    
    Expected output
    2
    2
    5
    4
    
  2. Example 2

    Input
    5 5
    1 2 1 2 8
    2
    3 4
    4
    2 3
    5 5 5 5 5 1 5 5
    2 4 3
    3 2 6
    5 3 2
    5 3 7
    5 3 1000000000000000000
    
    Expected output
    2
    3
    5
    4
    2