#ARC159E. [ARC159E] Difference Sum Query

[ARC159E] Difference Sum Query

Score : 900900 points

Problem Statement

You are given a positive integer NN, and MM pairs of positive integers: (a0,b0),,(aM1,bM1)(a_0,b_0),\ldots,(a_{M-1},b_{M-1}) (note that aia_i and bib_i start with index 00).

We have the following sequence of non-negative integers X=(x1,,xN)X=(x_1,\ldots,x_N).

  • xix_i is determined as follows.1. Let l=1l=1, r=Nr=N, and t=0t=0. 2. Let $m=\left \lfloor \dfrac{a_{t \bmod M} \times l + b_{t \bmod M} \times r}{a_{t \bmod M} +b_{t \bmod M}} \right \rfloor$ (x\lfloor x \rfloor is the greatest integer not exceeding xx). If m=im=i, let xi=tx_i=t and terminate. 3. If li<ml \leq i \lt m, let r=m1r=m-1; otherwise, let l=m+1l=m+1. Increment tt by 11 and return to step 2.
  • Let l=1l=1, r=Nr=N, and t=0t=0.
  • Let $m=\left \lfloor \dfrac{a_{t \bmod M} \times l + b_{t \bmod M} \times r}{a_{t \bmod M} +b_{t \bmod M}} \right \rfloor$ (x\lfloor x \rfloor is the greatest integer not exceeding xx). If m=im=i, let xi=tx_i=t and terminate.
  • If li<ml \leq i \lt m, let r=m1r=m-1; otherwise, let l=m+1l=m+1. Increment tt by 11 and return to step 2.

Find j=cidi1xjxj+1\sum_{j=c_i}^{d_i-1} |x_j - x_{j+1}| for i=1,2,,Qi=1,2,\ldots,Q. It can be proved that the answers are at most 101810^{18} under the constraints of this problem.

Constraints

  • 2N10152 \leq N \leq 10^{15}
  • 1M1001 \leq M \leq 100
  • 1ai,bi10001 \leq a_i,b_i \leq 1000
  • $\max \left (\dfrac{a_i}{b_i},\dfrac{b_i}{a_i}\right ) \leq 2$
  • 1Q1041 \leq Q \leq 10^4
  • 1ci<diN1 \leq c_i \lt d_i \leq N
  • All values in the input are integers.

Input

The input is given from Standard Input in the following format:

NN MM

a0a_0 b0b_0

\vdots

aM1a_{M-1} bM1b_{M-1}

QQ

c1c_1 d1d_1

\vdots

cQc_Q dQd_Q

Output

Print QQ lines. The xx-th line should contain the answer to the question for i=xi=x.

5 1
1 1
3
1 2
2 4
3 5
1
3
2

We have X=(1,2,0,1,2)X=(1,2,0,1,2). For example, x1x_1 is determined as follows.

  • Let l=1l=1, r=5(=N)r=5(=N), and t=0t=0.
  • Let $m=3(=\left \lfloor \dfrac{1 \times 1 + 1 \times 5}{1+1} \right \rfloor)$.
  • Since l1<ml \leq 1 \lt m, let r=2(=m1)r=2(=m-1). Increment tt by 11 to 11.
  • Let $m=1(= \left \lfloor \dfrac{1 \times 1 + 1 \times 2}{1+1} \right \rfloor )$. Since m=1m=1, let x1=1(=t)x_1=1(=t) and terminate.

The answer to the question for (c1,d1)(c_1,d_1), for example, is $\sum_{j=c_i}^{d_i-1} |x_j - x_{j+1}| = |x_1-x_2| = 1$.

1000000000000000 2
15 9
9 15
3
100 10000
5000 385723875
150 17095708
19792
771437738
34191100