This page is still under construction.

Parts of this page are still being built. What you see may change.

Vampire Tunnels

Time limit2sMemory limit512 MB

Summary
Find the shortest path from node 0 to N-1 where the total length of above-ground edges is at most S.
Level

Medium6 of 10

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

Problem

You are a vampire, and you want to travel from point 0 to point N−1N-1. You may walk above ground, exposed to sunlight, or avoid the sun by travelling underground through secret tunnels. Both the tunnels and the above-ground paths are bidirectional.

You move at a constant speed of 11 unit of distance per second, so travelling along a path of length dd takes dd seconds. You may be exposed to sunlight for at most SS seconds in total. Minimize the total travel time from point 0 to point N−1N-1 while respecting this limit.

Input

The first line contains the integer SS (0≤S≤36000 \le S \le 3600), the maximum number of seconds you may be exposed to the sun.

The second line contains two integers NN (2≤N≤16002 \le N \le 1600) and EE (1≤E≤100001 \le E \le 10000), separated by a single space: the number of points and the number of connections. The points are numbered from 0 to N−1N-1.

Each of the next EE lines contains four integers ss, tt, dd, uu describing one connection:

  • ss, tt (0≤s,t≤N−10 \le s, t \le N-1, s≠ts \ne t): the two endpoints of the connection
  • dd (1≤d≤100001 \le d \le 10000): the distance (travel time) between ss and tt
  • uu: 11 if the connection is above ground (exposed to sun), or 00 if it is a tunnel (underground, no sun exposure)

Output

Output a single integer: the minimum time needed to travel from point 0 to point N−1N-1 while spending at most SS seconds exposed to the sun. If no path satisfies this constraint, output −1-1.

Examples1

  1. Example 1

    Input
    3
    4 6
    0 1 3 1
    0 2 4 1
    0 3 10 1
    1 2 3 0
    1 3 1 1
    2 3 3 0
    
    Expected output
    9