Under construction

Still being built. Things may change

Raging River

Time limit2sMemory limit1024 MB

Summary
Find the minimum total time to get all P people across when each plank can be crossed only once, or the fewest people who must stay behind.
Level

Medium6 of 10

Topics
Graph, Shortest path
Solved
No attempts yet

Problem

Sally and her friends are trying to cross safely from one bank of a raging river to another. Boulders are scattered within the river. Log planks connect the banks to some of the boulders, and some pairs of boulders to each other.

Sally crosses the river first. She starts at the left bank and crosses one plank at a time, aiming to reach the right bank. Walking across a plank takes one second. Each time she crosses a plank, that plank collapses into the river, so neither Sally nor her friends can use it again. After Sally reaches the right bank safely, another friend tries to cross, and so on, until everyone who can make it has crossed.

Given the graph of banks, boulders, and planks, and the number of people who need to cross, find the smallest total time (in seconds) required for everyone to cross safely. If not everyone can cross, find the minimum number of people nn who must be left behind.

Input

The first line contains three integers PP, RR, and LL: the number of people PP who must cross, the number of boulders RR in the river, and the number of logs LL that span boulders and river banks. These satisfy 1≤P≤101 \leq P \leq 10, 0≤R≤10000 \leq R \leq 1000, and 0≤L≤10000 \leq L \leq 1000.

Each of the next LL lines contains two integers E1E_1 and E2E_2, the endpoints of one log. Each value is in the range [−2,R−1][-2, R-1]. The value −2-2 is the left river bank, −1-1 is the right river bank, and every other value is a boulder.

Every log has two distinct endpoints, and no two logs span the same pair of boulders or banks. The right bank or some boulders may not be reachable from the left bank.

Output

If all PP people can reach the right bank, print one integer: the minimum total time (in seconds) for all of them to cross.

Otherwise, print n people left behind, where nn is the least number of people who must stay on the left bank.

Examples2

  1. Example 1

    Input
    2 4 7
    -2 0
    0 -1
    -2 1
    1 0
    2 1
    2 3
    3 -1
    
    Expected output
    6
    
  2. Example 2

    Input
    3 2 5
    -2 0
    -2 1
    0 1
    1 -1
    0 -1
    
    Expected output
    1 people left behind