Score : 900 points
Problem Statement
You are given a positive integer N, and M pairs of positive integers: (a0,b0),…,(aM−1,bM−1) (note that ai and bi start with index 0).
We have the following sequence of non-negative integers X=(x1,…,xN).
- xi is determined as follows.1. Let l=1, r=N, and t=0.
2. Let m=⌊atmodM+btmodMatmodM×l+btmodM×r⌋ (⌊x⌋ is the greatest integer not exceeding x). If m=i, let xi=t and terminate.
3. If l≤i<m, let r=m−1; otherwise, let l=m+1. Increment t by 1 and return to step 2.
- Let l=1, r=N, and t=0.
- Let m=⌊atmodM+btmodMatmodM×l+btmodM×r⌋ (⌊x⌋ is the greatest integer not exceeding x). If m=i, let xi=t and terminate.
- If l≤i<m, let r=m−1; otherwise, let l=m+1. Increment t by 1 and return to step 2.
Find ∑j=cidi−1∣xj−xj+1∣ for i=1,2,…,Q.
It can be proved that the answers are at most 1018 under the constraints of this problem.
Constraints
- 2≤N≤1015
- 1≤M≤100
- 1≤ai,bi≤1000
- max(biai,aibi)≤2
- 1≤Q≤104
- 1≤ci<di≤N
- All values in the input are integers.
The input is given from Standard Input in the following format:
N M
a0 b0
⋮
aM−1 bM−1
Q
c1 d1
⋮
cQ dQ
Output
Print Q lines. The x-th line should contain the answer to the question for i=x.
We have X=(1,2,0,1,2). For example, x1 is determined as follows.
- Let l=1, r=5(=N), and t=0.
- Let m=3(=⌊1+11×1+1×5⌋).
- Since l≤1<m, let r=2(=m−1). Increment t by 1 to 1.
- Let m=1(=⌊1+11×1+1×2⌋). Since m=1, let x1=1(=t) and terminate.
The answer to the question for (c1,d1), for example, is ∑j=cidi−1∣xj−xj+1∣=∣x1−x2∣=1.