Under construction

Still being built. Things may change

Cheap Traveling

Time limit2sMemory limit512 MB

Summary
Find a route from village 1 to N whose total fare is at most S and whose total travel time is smallest; rides and villages may repeat.
Level

Medium7 of 10

Topics
Shortest path, Graph, Dynamic programming, Greedy
Solved
No attempts yet

Problem

Ivan has to pay out of his own pocket for the trip to the town where the next programming contest is held, and he has only SS euro. So he looked up the public transport timetables and the fares in advance.

Call Ivan's home village 11, the village where the contest takes place NN, and the other villages he may pass through 2,3,…,N−12, 3, \dots, N-1. Ivan found MM bus lines. Each line connects village vv and village ww, takes tt hours in either direction, and costs ee euro per ride. Several buses may connect the same two villages, and those buses may differ in travel time and in fare.

Write a program that finds a route from village 11 to village NN whose fares add up to at most SS euro. If several such routes exist, the program must find one where the total time spent sitting in buses is smallest.

Every ride on a line costs that line's fare ee and takes that line's time tt. A route may pass through the same village or the same line more than once, and each pass adds the fare and the time again.

If NN is 11, the start is already the destination, so the total time is 00.

Input

The first line contains the positive integers SS, NN and MM, with S≤2000S \le 2000, N≤3000N \le 3000 and M≤5000M \le 5000.

Each of the next MM lines contains four integers vv, ww, tt and ee describing one bus line, with 1≤v≤N1 \le v \le N, 1≤w≤N1 \le w \le N, 1≤t≤1001 \le t \le 100 and 1≤e≤1001 \le e \le 100.

Output

Print the total travel time of the route found, on a single line. If no route costs at most SS euro, print -1.

Examples2

  1. Example 1

    Input
    7 4 6
    1 2 2 5
    1 3 2 2
    1 4 7 3
    2 3 1 2
    2 4 2 3
    3 4 5 2
    
    Expected output
    5
    
  2. Example 2

    Input
    4 4 6
    1 2 2 5
    1 3 2 2
    1 4 7 5
    2 3 1 2
    2 4 2 3
    3 4 5 3
    
    Expected output
    -1