Prefix MEX#12785

Prefix MEX

2 seconds
256 megabytes
Very hard

For an array of integers b=[b_1,b_2,\ldots,b_m], let denote the smallest non-negative integer that does not appear in the array .

Define as an array of length such that

f(b)_i=\operatorname{MEX}([b_1,b_2,\ldots,b_i]).

In other words, the -th element of the array is equal to the MEX of the prefix of array of length .

Also define the function :

g(0,b)=b,

and for k\ge 1

g(k,b)=f(g(k-1,b)).

That is, g(k,b) is the result of applying the function to array exactly times.

You are given an array a=[a_1,a_2,\ldots,a_n].

You need to answer independent queries. Each query is given by five integers , , , , .

For each query, consider the array

b=[a_L,a_{L+1},\ldots,a_R]

and construct

d=g(k,b).

For this query, you need to find the value

d_l+d_{l+1}+\ldots+d_r.

The queries do not modify the original array .

Input

The first line contains two integers and (1 \le n,q \le 3 \cdot 10^5) — the length of the array and the number of queries, respectively.

The second line contains integers a_1,a_2,\ldots,a_n (0 \le a_i \le n).

Each of the next lines contains five integers , , , , (1 \le L \le R \le n, 1 \le k \le 10^9, 1 \le l \le r \le R-L+1).

Output

For each query, output one integer — the sum

d_l+d_{l+1}+\ldots+d_r,

where

d=g(k,[a_L,a_{L+1},\ldots,a_R]).

Print the answers to the queries in separate lines.

Examples

Example 1

Loading
Loading

Note

In the first query, we have

b=[a_2,a_3,a_4]=[2,0,1].

The prefix MEX values of this array are

f(b)=[0,1,3].

Since k=1, we have d=[0,1,3]. We need to find the sum of the elements from position to position :

d_2+d_3=1+3=4.

In the second query, we have

b=[1,2,0,1,3,1].

After the first application of function , we get

f(b)=[0,0,3,3,4,4].

Apply function once more:

f(f(b))=[1,1,1,1,1,1].

Thus,

d=g(2,b)=[1,1,1,1,1,1],

so the sum of all its elements is

1+1+1+1+1+1=6.

In the third query, consider the array

b=[a_4]=[1].

Its only prefix has MEX equal to , so

d=f(b)=[0].

Therefore, the answer is .

Scoring

  1. Subtask ( points): L = R for all queries.

  2. Subtask ( points): a_i = a_{i+1} for all 1 \le i < n.

  3. Subtask ( points): k = 10^9 for all queries.

  4. Subtask ( points): n,q,k \le 100.

  5. Subtask ( points): n,q \le 1000.

  6. Subtask ( points): l \ne r, k \ne 2 for all queries.

  7. Subtask ( points): L = 1, k \ne 2 for all queries.

  8. Subtask ( points): k = 2 for all queries.

  9. Subtask ( points): L = 1 for all queries.

  10. Subtask ( points): No additional constraints.