#P2620. 虫洞
虫洞
Description
To simplify the problem, we set up a one-dimensional coordinate system, with Earth at position , and applepi’s destination at a positive integer position .
In each unit time, applepi can move an integer no greater than toward the positive direction. A wormhole is represented as a pair , meaning that if after a move applepi is at position , he is immediately transported to position .
Note that if applepi passes through position during a move, he will not be transported because he moves extremely fast. Also, applepi cannot move in the negative direction, except when caused by a wormhole.
Now applepi asks you to compute the minimum number of unit times needed to reach the destination.
Input Format
The input contains multiple test cases.
For each test case, the first line contains three positive integers , representing the destination position, the movement limit, and the number of wormholes. The next lines each contain two integers and , representing a wormhole.
The last line of the input file is an integer , indicating the end of input.
Output Format
For each test case, output the result on a single line.
28 3 5
2 18
5 13
12 6
17 25
20 15
50 6 1
9 45
0
4
3
Hint
- For of the testdata, .
- For of the testdata, , , , there is no wormhole with or , and the input guarantees the destination is reachable.
Translated by ChatGPT 5
京公网安备 11011102002149号