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

#FT0000026. Khoảng điểm xếp hạng (Rated Range)

HỌC THEO LỘ TRÌNH

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

2 lộ trình

Khoảng điểm xếp hạng (Rated Range)

Rated Range

Source: AtCoder

Version: Phuoc Hung OJ Extended

Problem Statement

Takahashi plans to participate in nn contests, in order from contest 11 to contest nn. Contest ii has an eligible rating interval [Li,Ri][L_i,R_i], including both endpoints.

During contest ii, inspect his rating immediately before that contest. If it belongs to [Li,Ri][L_i,R_i], the rating increases by exactly one; otherwise it remains unchanged. The resulting rating is used to determine eligibility in contest i+1i+1. Thus, testing every contest against the initial rating would be incorrect.

There are qq queries. For each independently specified initial rating XX, determine his rating after all nn contests. Each query starts anew from its own initial XX and uses the same contest sequence; the result of a preceding query has no effect.

Input

  • Line 1: integer n, the number of contests.
  • Next nn lines: line ii contains two integers L_i R_i, the inclusive lower and upper limits of the rating interval for contest ii.
  • Next line: integer q, the number of independent queries.
  • Final qq lines: line jj contains integer X_j, the initial rating for query jj.

Output

Print exactly qq lines. Line jj is the final rating when query jj starts from rating XjX_j.

Subtasks

Subtask 1 (20 points):

  • 1≤n≤241\le n\le 24.
  • 1≤q≤301\le q\le 30.
  • 1≤Li≤Ri≤5000001\le L_i\le R_i\le 500000 for all 1≤i≤n1\le i\le n.
  • 1≤Xj≤5000001\le X_j\le 500000 for all 1≤j≤q1\le j\le q.

Subtask 2 (30 points):

  • 1≤n≤12001\le n\le 1200.
  • 1≤q≤16001\le q\le 1600.
  • 1≤Li≤Ri≤5000001\le L_i\le R_i\le 500000 for all 1≤i≤n1\le i\le n.
  • 1≤Xj≤5000001\le X_j\le 500000 for all 1≤j≤q1\le j\le q.

Subtask 3 (50 points):

  • 1≤n≤2000001\le n\le 200000.
  • 1≤q≤3000001\le q\le 300000.
  • 1≤Li≤Ri≤5000001\le L_i\le R_i\le 500000 for all 1≤i≤n1\le i\le n.
  • 1≤Xj≤5000001\le X_j\le 500000 for all 1≤j≤q1\le j\le q.

Examples

Input

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

Output

6
6
8

Explanation

The five contest rating intervals, in order, are [1,5][1,5], [1,3][1,3], [3,6][3,6], [2,4][2,4], and [4,7][4,7]. Each query independently starts from its specified rating.

  1. Starting at X=3X=3: contest 1 increases 3→43\to4 because 3∈[1,5]3\in[1,5]; contest 2 keeps 44 because 4∉[1,3]4\notin[1,3]; contest 3 increases 4→54\to5; contest 4 keeps 55; contest 5 increases 5→65\to6. Print 6.

  2. Starting at X=2X=2: contest 1 increases 2→32\to3, contest 2 increases 3→43\to4, contest 3 increases 4→54\to5, contest 4 keeps 55, and contest 5 increases 5→65\to6. Print 6.

  3. Starting at X=5X=5: contest 1 increases 5→65\to6, contest 2 keeps 66, contest 3 increases 6→76\to7, contest 4 keeps 77, and contest 5 increases 7→87\to8. Print 8.

The resulting ratings are 6,6,86,6,8, so the output lines are 6, 6, and 8.