This page is still under construction.

Parts of this page are still being built. What you see may change.

Shopping

Time limit1sMemory limit256 MB

Summary
A shopper starts at the entrance, visits each of N shops in a row under the given order constraints, and ends at the exit with the shortest total walk.
Level

Medium7 of 10

Topics
Dynamic programming, Intervals
Solved
No attempts yet

Problem

Your friend goes shopping. The mall runs along a straight street, where NN shops numbered 1 to NN stand in a row at regular intervals. Each shop has one door, and the distance between the doors of two neighbouring shops is one unit length. The door of shop kk is kk units from the entrance, and the exit is N+1N+1 units from the entrance.

She starts at the entrance, visits all NN shops, and finishes at the exit. Visiting a shop means standing at its door and stepping inside.

There are mm restrictions on the visiting order. Each restriction is a pair of integers (c,d)(c, d) with c<dc < d, and it means she must visit shop cc after she visits shop dd. For example, if she wants to pick a dress before choosing heels, she visits the boutique first and the shoe store later. When the boutique is farther from the entrance than the shoe store, she walks past the door of the shoe store, goes to the boutique, and then walks back to the shoe store.

As long as the visiting order satisfies every restriction, she can visit the remaining shops in any order she likes.

Write a program that computes the minimum walking length she needs to move from the entrance to the exit. Walking inside a shop does not count.

Input

The first line contains two integers NN and mm, where NN is the number of shops and mm is the number of restrictions. (1≤N≤10001 \le N \le 1000, 0≤m≤5000 \le m \le 500)

Each of the next mm lines contains one restriction. Line ii contains two integers cic_i and did_i, meaning she must visit shop cic_i after she visits shop did_i. (1≤ci<di≤N1 \le c_i < d_i \le N)

No pair is given twice. That is, there are no distinct jj and kk with cj=ckc_j = c_k and dj=dkd_j = d_k.

Output

Print on one line the minimum walking length she needs to move from the entrance to the exit. Do not count the walking she does inside a shop.

Examples5

  1. Example 1

    Input
    10 3
    3 7
    8 9
    2 5
    
    Expected output
    23
    
  2. Example 2

    Input
    10 3
    8 9
    6 7
    2 4
    
    Expected output
    19
    
  3. Example 3

    Input
    10 0
    
    Expected output
    11
    
  4. Example 4

    Input
    10 6
    6 7
    4 5
    2 5
    6 9
    3 5
    6 8
    
    Expected output
    23
    
  5. Example 5

    Input
    1000 8
    3 4
    6 1000
    5 1000
    7 1000
    8 1000
    4 1000
    9 1000
    1 2
    
    Expected output
    2997