#P2620. 虫洞

虫洞

Description

To simplify the problem, we set up a one-dimensional coordinate system, with Earth at position 00, and applepi’s destination at a positive integer position WW.

In each unit time, applepi can move an integer no greater than SS toward the positive direction. A wormhole is represented as a pair (B,E)(B, E), meaning that if after a move applepi is at position BB, he is immediately transported to position EE.

Note that if applepi passes through position BB 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 W,S,PW, S, P, representing the destination position, the movement limit, and the number of wormholes. The next PP lines each contain two integers BB and EE, representing a wormhole.

The last line of the input file is an integer 00, 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 30%30\% of the testdata, W1000W \le 1000.
  • For 100%100\% of the testdata, W109W \le 10^9, 2S62 \le S \le 6, 1P401 \le P \le 40, there is no wormhole with B=0B = 0 or B=WB = W, and the input guarantees the destination is reachable.

Translated by ChatGPT 5