Under construction

Still being built. Things may change

Perm Query

Time limit2sMemory limit512 MB

Summary
Given a permutation whose cycles all have length at most 40, answer queries summing iterates of the permutation on an interval until the interval returns to the identity.
Level

Hard8 of 10

Topics
Math, Prefix sum, Implementation, Brute force
Solved
No attempts yet

Problem

You are given a permutation (p(1),p(2),…,p(N))(p(1), p(2), \dots, p(N)) of {1,2,…,N}\{1, 2, \dots, N\}. You are also given QQ queries of the form (li,ri)(l_i, r_i). For each query, output the result of the following pseudocode.

  1. Set ret:=0ret := 0 and (x(1),x(2),…,x(N)):=(1,2,…,N)(x(1), x(2), \dots, x(N)) := (1, 2, \dots, N).
  2. For each i∈{1,2,…,N}i \in \{1, 2, \dots, N\}, set y(i):=p(x(i))y(i) := p(x(i)).
  3. For each i∈{1,2,…,N}i \in \{1, 2, \dots, N\}, set x(i)=y(i)x(i) = y(i).
  4. ret:=ret+x(li)+x(li+1)+⋯+x(ri)ret := ret + x(l_i) + x(l_i+1) + \dots + x(r_i)
  5. If (x(li),x(li+1),…,x(ri))=(li,li+1,…,ri)(x(l_i), x(l_i+1), \dots, x(r_i)) = (l_i, l_i+1, \dots, r_i), output (ret mod 109+7)(ret \bmod 10^9+7) and stop. Otherwise, go back to step 2.

Input

The input is given in the following format.

NN QQ

p(1)p(1) p(2)p(2) …\dots p(N)p(N)

l1l_1 r1r_1

…\dots

lQl_Q rQr_Q

Output

Output the answer for each query, one per line.

Constraints

  • 1≤N≤1051 \le N \le 10^5
  • 1≤Q≤1041 \le Q \le 10^4
  • (p(1),p(2),…,p(N))(p(1), p(2), \dots, p(N)) is a permutation of (1,2,…,N)(1, 2, \dots, N).
  • For each ii, there exists some 1≤k≤401 \le k \le 40 such that pk(i)=ip^k(i) = i. Here pk(i)p^k(i) is p(p(p(…p(i)… )))p(p(p(\dots p(i) \dots))) with pp appearing kk times.
  • 1≤li≤ri≤N1 \le l_i \le r_i \le N

Examples2

  1. Example 1

    Input
    5 2
    5 1 2 3 4
    1 1
    2 4
    
    Expected output
    15
    45
    
  2. Example 2

    Input
    10 5
    3 1 2 5 4 10 6 7 9 8
    1 10
    1 5
    3 3
    5 10
    9 10
    
    Expected output
    660
    90
    6
    178
    67