#P4768. Minimize Walking Distance in Magic City

    ID: 18012 Type: Default 1000ms 256MiB

Minimize Walking Distance in Magic City

Minimize Walking Distance in Magic City

In the magical city where rain is frequent, the urban area is modeled as an undirected connected graph with nn nodes and mm edges. Each edge is described by its length ll and altitude aa. Due to heavy seasonal rains, roads accumulate water. The drainage system makes sure that the flooded roads are exactly those with the lowest altitudes: when the water level is set to pp, every road whose altitude p\leq p is flooded. Cars cannot travel through flooded roads, but pedestrians can go along any road.\n\nYazid, a local resident and competitor, has his home at node 11. Over QQ days, on each day he provides a starting node vv and a water level pp. Starting at vv, he is provided with a car which can drive only on non-flooded (safe) edges (i.e. edges with altitude >p> p). At any node he may choose to abandon the car and complete his journey on foot (which can use any road). However, once he leaves the car, he must continue walking, and the car he left behind will not be available later (cars are reset on each day).\n\nHelp Yazid minimize the total walking distance—the sum of the lengths of the edges he must walk on—on his journey to his home. Equivalently, let d(u)d(u) be the shortest walking distance (using any roads) from node uu to node 11. On a given day with starting node vv and water level pp, let SS be the set of nodes reachable from vv using roads with altitude >p> p (i.e. via car). The answer is ( \min_{u \in S} d(u) ).\n\nNote that the graph is connected (by all roads) and the car is available fresh each day.

inputFormat

The first line contains two integers nn and mm, representing the number of nodes and edges.\n\nThe next mm lines each contain four integers uu, vv, ll, and aa, describing an edge between nodes uu and vv with length ll and altitude aa.\n\nThe following line contains an integer QQ, the number of queries.\n\nEach of the next QQ lines contains two integers vv and pp, which are the starting node and the water level for that day.

outputFormat

For each query, output a single integer representing the minimum total walking distance from the starting node vv (given the water level pp) to home at node 11.

sample

4 4
1 2 3 5
2 3 2 3
3 4 4 6
2 4 1 2
2
3 4
4 2
4

0

</p>