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

#BS0000438. Ngày cuối cùng có thể vượt qua vùng đất (Last Day Where You Can Still Cross)

HỌC THEO LỘ TRÌNH

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

1 lộ trình

Ngày cuối cùng có thể vượt qua vùng đất (Last Day Where You Can Still Cross)

Last Day Where You Can Still Cross

Source: LeetCode

Version: Phuoc Hung OJ Extended

Problem Statement

A rectangular region consists of nn rows and mm columns, numbered from 11 to nn and from 11 to mm, respectively. On day 00, all cells are dry land.

Every day, exactly one previously dry cell becomes flooded. The cell flooded on day kk has coordinates (rk,ck)(r_k,c_k) and remains flooded on every subsequent day. You are given the flooding order of all nmnm cells.

After the cell scheduled for a particular day has flooded, you wish to walk from the first row to the last row. You may start at any dry cell in row 11 and finish at any dry cell in row nn. Each move must go to a dry cell sharing a side with the current cell, in one of the four directions. You cannot leave the region or enter a flooded cell.

Find the latest day on which such a route still exists.

Input

  • The first line contains two integers n,mn,m, the numbers of rows and columns.
  • The next nmnm lines each contain two integers; line kk gives coordinates rk,ckr_k,c_k of the cell flooded on day kk.

Output

Print one integer: the latest day on which walking from row 11 to row nn is still possible.

Subtasks

  • Subtask 1 (20 points): 2≤n,m≤200002\le n,m\le 20000; 4≤nm≤364\le nm\le 36; 1≤ri≤n1\le r_i\le n, 1≤ci≤m1\le c_i\le m for all 1≤i≤nm1\le i\le nm; nmnm coordinate pairs are pairwise distinct.
  • Subtask 2 (30 points): 2≤n,m≤200002\le n,m\le 20000; 4≤nm≤4004\le nm\le 400; 1≤ri≤n1\le r_i\le n, 1≤ci≤m1\le c_i\le m for all 1≤i≤nm1\le i\le nm; nmnm coordinate pairs are pairwise distinct.
  • Subtask 3 (50 points): 2≤n,m≤200002\le n,m\le 20000; 4≤nm≤200004\le nm\le 20000; 1≤ri≤n1\le r_i\le n, 1≤ci≤m1\le c_i\le m for all 1≤i≤nm1\le i\le nm; nmnm coordinate pairs are pairwise distinct.

Examples

Example 1

Input

2 2
1 1
2 1
1 2
2 2

Output

2

Explanation

On day 11, (1,1)(1,1) floods; on day 22, (2,1)(2,1) floods. Both cells in column 22 are still dry, giving a vertical crossing. On day 33, (1,2)(1,2) floods too, leaving no land in the top row. The last possible day is 22.

Illustration

Example 2

Input

2 2
1 1
1 2
2 1
2 2

Output

1

Explanation

On day 11, (1,1)(1,1) floods but column 22 remains dry, so (1,2)(1,2) can reach (2,2)(2,2). On day 22, (1,2)(1,2) floods, eliminating all starting cells. Thus the answer is 11.

Example 3

Input

3 3
1 2
2 1
3 3
2 2
1 1
1 3
2 3
3 2
3 1

Output

3

Explanation

After day 33, (1,2),(2,1),(3,3)(1,2),(2,1),(3,3) are flooded. The route (1,3),(2,3),(2,2),(3,2)(1,3),(2,3),(2,2),(3,2) remains dry. On day 44, (2,2)(2,2) also floods: (1,1)(1,1) is isolated, and the route from (1,3)(1,3) stops at (2,3)(2,3) without reaching the bottom. Hence day 33 is the last possible day.