Under construction

Still being built. Things may change

Escape Route 2

Time limit2sMemory limit1024 MB

Summary
Given daily repeating flight schedules between consecutive cities, find the minimum travel time from city L to city R for each query.
Level

Hard8 of 10

Topics
Dynamic programming, Binary search, Sorting
Solved
No attempts yet

Problem

The IOI Kingdom has NN cities in a row from west to east, numbered from 11 to NN starting from the west.

The IOI Kingdom uses Byou as its unit of time. A day is divided into TT units of time. The moment xx Byou (0≤x<T0 \le x < T) after the start of a day is called time xx. So when 1 Byou passes from time T−1T-1 on some day, it becomes time 00 the next day.

JOI Group is one of the secret sects in the IOI Kingdom. Members must avoid the country's checkpoints, so they may only use flights operated by JOY Airlines for travel between cities.

JOY Airlines operates MiM_i flights departing from city ii (1≤i≤N−11 \le i \le N-1). The jj-th flight (1≤j≤Mi1 \le j \le M_i) departs from city ii at time Ai,jA_{i,j} every day and arrives at city i+1i+1 at time Bi,jB_{i,j} on the same day, where Ai,j<Bi,jA_{i,j} < B_{i,j}. These flights allow convenient transfers. A member can also leave a city right after arriving, or stay overnight at the airline's airports.

The JOI Group has QQ members, numbered from 11 to QQ. Member kk (1≤k≤Q1 \le k \le Q) has an operational base in city LkL_k and a living base in city RkR_k. Each member wants the minimum time needed to travel from LkL_k to RkR_k, choosing the departure time from LkL_k and the flights to take.

Given the flight information and the members' bases, write a program that finds, for each member kk, the minimum time to travel from city LkL_k to city RkR_k.

Input

Read the following data from standard input.

N T
M_1
A_{1,1} B_{1,1}
A_{1,2} B_{1,2}
...
A_{1,M_1} B_{1,M_1}
M_2
...
M_{N-1}
...
Q
L_1 R_1
L_2 R_2
...
L_Q R_Q

Output

Output QQ lines to standard output. On the kk-th line, output the minimum time required for member kk to travel from city LkL_k to city RkR_k.

Constraints

  • 2≤N≤100 0002 \le N \le 100\,000.
  • 2≤T≤1092 \le T \le 10^9.
  • Mi≥1M_i \ge 1 (1≤i≤N−11 \le i \le N-1).
  • M1+M2+⋯+MN−1≤100 000M_1 + M_2 + \cdots + M_{N-1} \le 100\,000.
  • 0≤Ai,j<Bi,j<T0 \le A_{i,j} < B_{i,j} < T (1≤i≤N−11 \le i \le N-1, 1≤j≤Mi1 \le j \le M_i).
  • 1≤Q≤300 0001 \le Q \le 300\,000.
  • 1≤Lk<Rk≤N1 \le L_k < R_k \le N (1≤k≤Q1 \le k \le Q).
  • All given values are integers.

Examples2

  1. Example 1

    Input
    4 10000
    1
    100 300
    2
    200 400
    300 600
    1
    500 600
    3
    1 3
    2 4
    1 4
    
    Expected output
    500
    400
    10500
    
  2. Example 2

    Input
    6 10000
    1
    100 300
    1
    400 700
    1
    500 600
    1
    300 900
    1
    200 800
    1
    1 6
    
    Expected output
    30700