Shopping
Time limit1sMemory limit256 MB
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 shops numbered 1 to 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 is units from the entrance, and the exit is units from the entrance.
She starts at the entrance, visits all shops, and finishes at the exit. Visiting a shop means standing at its door and stepping inside.
There are restrictions on the visiting order. Each restriction is a pair of integers with , and it means she must visit shop after she visits shop . 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 and , where is the number of shops and is the number of restrictions. (, )
Each of the next lines contains one restriction. Line contains two integers and , meaning she must visit shop after she visits shop . ()
No pair is given twice. That is, there are no distinct and with and .
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.