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

#LCA0000016. Cây tăng trưởng vô hạn (Evergrowing Tree)

HỌC THEO LỘ TRÌNH

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

1 lộ trình

Cây tăng trưởng vô hạn (Evergrowing Tree)

Evergrowing Tree

Source: AtCoder

Version: Phuoc Hung OJ Extended

Problem Statement

Consider an infinite NN-ary rooted tree: every vertex has exactly NN children. The root is labeled 11. All positive integers label vertices in breadth-first order, from upper levels to lower levels and from left to right within a level.

For each of QQ vertex pairs (vi,wi)(v_i,w_i), find their lowest common ancestor: the deepest vertex that is an ancestor of both, considering each vertex an ancestor of itself.

The tree has infinitely many vertices; print the required labels without materializing it.

Input

  • The first line contains N,QN,Q.
  • Each of the next QQ lines contains vi,wiv_i,w_i, with vi<wiv_i<w_i.

Output

Print QQ lines; each line gives the lowest common ancestor label for one pair.

Subtasks

  • Subtask 1 (20 points): N≤10N\le10; Q≤60Q\le60; v,w≤100v,w\le100; 1≤N≤1091\le N\le10^9; 1≤Q≤1051\le Q\le10^5; 1≤vi<wi≤1091\le v_i<w_i\le10^9.
  • Subtask 2 (30 points): N≤104N\le10^4; Q≤3000Q\le3000; v,w≤106v,w\le10^6; 1≤N≤1091\le N\le10^9; 1≤Q≤1051\le Q\le10^5; 1≤vi<wi≤1091\le v_i<w_i\le10^9.
  • Subtask 3 (50 points): 1≤N≤1091\le N\le10^9; 1≤Q≤1051\le Q\le10^5; 1≤vi<wi≤1091\le v_i<w_i\le10^9.

Examples

Input

3 3
5 7
8 11
3 9

Output

2
1
3

Explanation

For N=3N=3, vertices 55 and 77 share parent 22. Vertices 88 and 1111 share only root 11, while vertex 33 is an ancestor of 99.