ROADS - Roads

no tags 

N cities named with numbers 1 ... N are connected with one-way roads. Each road has two parameters associated with it: the road length and the toll that needs to be paid for the road (expressed in the number of coins). Bob and Alice used to live in the city 1. After noticing that Alice was cheating in the card game they liked to play, Bob broke up with her and decided to move away - to the city N. He wants to get there as quickly as possible, but he is short on cash. We want to help Bob to find the shortest path from the city 1 to the city N that he can afford with the amount of money he has.

Input

The input begins with the number t of test cases. Then t test cases follow. The first line of the each test case contains the integer K, 0 <= K <= 10000, maximum number of coins that Bob can spend on his way. The second line contains the integer N, 2 <= N <= 100, the total number of cities. The third line contains the integer R, 1 <= R <= 10000, the total number of roads. Each of the following R lines describes one road by specifying integers S, D, L and T separated by single blank characters : S is the source city, 1 <= S <= N D is the destination city, 1 <= D <= N L is the road length, 1 <= L <= 100. T is the toll (expressed in the number of coins), 0 <= T <= 100 Notice that different roads may have the same source and destination cities.

Output

For each test case, output a single line contain the total length of the shortest path from the city 1 to the city N whose total toll is less than or equal K coins. If such path does not exist, output -1.

Example

Input:
2
5
6
7
1 2 2 3
2 4 3 3
3 4 2 4
1 3 4 1
4 6 2 1
3 5 2 0
5 4 3 2
0
4
4
1 4 5 2
1 2 1 0
2 3 1 1
3 4 1 0

Output:
11
-1

hide comments
vengatesh15: 2017-01-19 06:44:59

AC after 1 month..

aish_dutt: 2016-10-21 06:37:51

Using adj list , don't forget to clear vector :) :)

itissabbir: 2016-04-23 07:38:06

I used simple DP
runtime 100*10000

Last edit: 2016-04-23 07:38:36
Liquid_Science: 2016-03-02 18:23:15

" Notice that different roads may have the same source and destination cities." 1 WA due to this

naruto09: 2015-09-25 15:50:15

getting WA...checked on most of the test cases...cant catch the problem..:(

Shubham Bansal: 2015-05-26 20:13:04

finally a question with AC in 1 go :-)

Shubham Jadhav: 2015-05-02 22:20:58

finally, ac.. don't give up, keep trying

shubham: 2015-01-29 16:41:04

Last edit: 2015-01-29 16:42:04
Rahul Lingala: 2014-12-26 15:24:20

Very good question

M Sudeep Kumar: 2014-10-15 13:57:26

are the edges directed?


Added by:Duc
Date:2005-04-28
Time limit:7s
Source limit:50000B
Memory limit:1536MB
Cluster: Cube (Intel G860)
Languages:All except: ERL JS-RHINO NODEJS PERL6 VB.NET
Resource:Central European Olympiad in Informatics '98