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

#FT0000097. Các tấm ván bật (Springboards)

HỌC THEO LỘ TRÌNH

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

1 lộ trình

Các tấm ván bật (Springboards)

Springboards

Source: USACO

Version: Phuoc Hung OJ Extended

Problem Statement

Bessie starts at (0,0)(0,0) on a square grid and wants to reach (N,N)(N,N). She may walk only right (increasing xx) or up (increasing yy), never left or down. Walking distance is the sum of the lengths of her walking segments.

There are PP springboards. Springboard ii starts at (x1,i,y1,i)(x_{1,i},y_{1,i}) and ends at (x2,i,y2,i)(x_{2,i},y_{2,i}). Upon reaching its starting point, Bessie may instantly travel to the endpoint at zero walking cost. Every springboard moves neither left nor down: x1,i≤x2,ix_{1,i}\le x_{2,i} and y1,i≤y2,iy_{1,i}\le y_{2,i}. She may use or ignore each board.

All supplied springboard start and end locations are distinct. Find the minimum total walking distance required to reach (N,N)(N,N), excluding all distance traveled using springboards.

Input

The first line contains N,PN,P. Each of the next PP lines contains four integers x1,i,y1,i,x2,i,y2,ix_{1,i},y_{1,i},x_{2,i},y_{2,i} for one springboard.

Output

Print one integer: the minimum walking distance from (0,0)(0,0) to (N,N)(N,N).

Subtasks

  • Subtask 1 (20 points): 1≤N≤201\le N\le20; 1≤P≤101\le P\le10; 0≤x1,i≤x2,i≤N0\le x_{1,i}\le x_{2,i}\le N; 0≤y1,i≤y2,i≤N0\le y_{1,i}\le y_{2,i}\le N; all 2P2P springboard endpoint coordinates are pairwise distinct.
  • Subtask 2 (30 points): 1≤N≤1051\le N\le10^5; 1≤P≤10001\le P\le1000; 0≤x1,i≤x2,i≤N0\le x_{1,i}\le x_{2,i}\le N; 0≤y1,i≤y2,i≤N0\le y_{1,i}\le y_{2,i}\le N; all 2P2P springboard endpoint coordinates are pairwise distinct.
  • Subtask 3 (50 points): 1≤N≤1091\le N\le10^9; 1≤P≤1051\le P\le10^5; 0≤x1,i≤x2,i≤N0\le x_{1,i}\le x_{2,i}\le N; 0≤y1,i≤y2,i≤N0\le y_{1,i}\le y_{2,i}\le N; all 2P2P springboard endpoint coordinates are pairwise distinct.

Examples

Example 1

Input

3 2
0 1 0 2
1 2 2 3

Output

3

Explanation

Bessie walks from (0,0)(0,0) to (0,1)(0,1) (cost 11), uses the first board to reach (0,2)(0,2) for free, walks to (1,2)(1,2) (another 11), uses the second board to reach (2,3)(2,3) for free, and walks to (3,3)(3,3) (another 11). Total walking cost: 1+1+1=31+1+1=3. This is optimal because the two boards cannot save more than their fixed displacement, totaling 33 units.

Example 2

Input

2 1
0 0 2 2

Output

0

Explanation

The springboard starts at (0,0)(0,0) and ends at the target (2,2)(2,2). Bessie uses it immediately without walking, so the answer is 00, which is the minimum possible.