Problem list
Log in
#usaco0407 · USACO 2019-2020 January Gold

Springboards

Platinum I 2.0 s 256 MB

Bessie is in a 2D grid where walking is permitted only in directions parallel to one of the coordinate axes. She starts at the point $(0,0)$ and wishes to reach $(N,N)$ ($1\le N\le 10^9$). To help her out, there are $P$ ($1\le P\le 10^5$) springboards on the grid. Each springboard is at a fixed point $(x_1,y_1)$ and if Bessie uses it, she will land at a point $(x_2,y_2)$.

Bessie is a progress-oriented cow, so she only permits herself to walk up or right, never left nor down. Likewise, each springboard is configured to never go left nor down. What is the minimum distance Bessie needs to walk?

Input

The fist line contains two space-separated integers $N$ and $P$.

The next $P$ lines each contains four integers, $x_1$, $y_1$, $x_2$, $y_2$, where $x_1 \le x_2$ and $y_1 \le y_2.$

All springboard and target locations are distinct.

Output

Output a single integer, the minimum distance Bessie needs to walk to reach $(N,N)$.

Constraints

SCORING

  • Test cases 2-5 satisfy $P \le 1000$.
  • Test cases 6-15 satisfy no additional constraints.

Example 1

Input
3 2
0 1 0 2
1 2 2 3
Output
3

Bessie's best path is:

  • Bessie walks from (0,0) to (0,1) (1 unit).
  • Bessie springs to (0,2).
  • Bessie walks from (0,2) to (1,2) (1 unit).
  • Bessie springs to (2,3).
  • Bessie walks from (2,3) to (3,3) (1 unit).

The total walking length of Bessie's path is 3 units.

Problem credits: Pedro Paredes

Source
USACO 2019-2020 January Gold
Appears in
Not part of a ladder, contest or set yet.
Accepted 0 Submissions 0 Acceptance 0% Solvers 0

Discussion

Threads about this problem. Spoilers are collapsed; wrap hints in ||double bars||.

No discussion yet. Start a thread if something here needs explaining.

Recent submissions Open with filters
Code