PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#SRD0000149. Ốc sên Julia (Julia the Snail)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Ốc sên Julia (Julia the Snail)

Julia the Snail

Source: Codeforces

Version: Phuoc Hung OJ Extended

Problem Statement

Julia is a snail on a trunk of height nn. She may slide downward freely. Igor attaches mm ropes: rope ii has lower endpoint at height lil_i and upper endpoint at rir_i. Julia may climb a rope from its lower endpoint to its upper endpoint but cannot leave it midway. All upper endpoints rir_i are pairwise distinct.

There are qq independent queries. For each (x,y)(x,y), Julia starts at height xx and is never allowed below xx or above yy. Determine the highest trunk height she can reach by combining the permitted downward slides and upward rope climbs.

Input

  • First line: integer nn, the trunk height.
  • Second line: integer mm, the number of ropes.
  • The next mm lines: li,ril_i,r_i for rope ii.
  • Next line: integer qq, the number of queries.
  • Next qq lines: x,yx,y for each query.

Output

Print qq lines, one maximum reachable trunk height for each query.

Subtasks

  • Subtask 1 (20 points): 1≤n≤1001\le n\le 100; 1≤m≤1001\le m\le 100, 1≤q≤1001\le q\le 100; 1≤li≤ri≤n1\le l_i\le r_i\le n; all rir_i distinct; 1≤x≤y≤n1\le x\le y\le n.
  • Subtask 2 (30 points): 1≤n≤30001\le n\le 3000; 1≤m≤30001\le m\le 3000, 1≤q≤30001\le q\le 3000; 1≤li≤ri≤n1\le l_i\le r_i\le n; all rir_i distinct; 1≤x≤y≤n1\le x\le y\le n.
  • Subtask 3 (50 points): 1≤n≤1000001\le n\le 100000; 1≤m≤1000001\le m\le 100000, 1≤q≤1000001\le q\le 100000; 1≤li≤ri≤n1\le l_i\le r_i\le n; all rir_i distinct; 1≤x≤y≤n1\le x\le y\le n.

Examples

Example 1

Input

8
4
1 2
3 4
2 5
6 7
5
1 2
1 4
1 6
2 7
6 8

Output

2
2
5
5
7

Explanation

At start 11 with ceiling 22, rope (1,2)(1,2) yields 22. With ceiling 44, height 33 is unreachable, so the maximum remains 22. With ceiling 66, ropes (1,2)(1,2) then (2,5)(2,5) reach 55. From 22 with ceiling 77, Julia can reach 55 but cannot get to 66, the lower endpoint of (6,7)(6,7). From 66 with ceiling 88, the last rope reaches 77.