Navigation Nightmare
InterviewTime limit1sMemory limit1024 MB
Given roads added one at a time on a grid map, answer the Manhattan distance between two farms using only the first I roads, or -1 if it is not yet known.
- Level
Medium6 of 10
- Topics
- Union-find, Graph
- Solved
- No attempts yet
Problem
Farmer John's pastoral neighborhood has farms (), usually numbered 1 to . A series of vertical and horizontal roads connect the farms, where and each road has a length with . A map might look like the illustration below, where farms are labeled F1 to F7 and road lengths are shown in parentheses. The diagram is not to scale.
F1 --- (13) ---- F6 --- (9) ----- F3
| |
(3) |
| (7)
F4 --- (20) -------- F2 |
| |
(2) F5
|
F7
Each farm connects directly to at most four other farms by roads that run exactly north, south, east, or west. Farms are located only at road endpoints, and every endpoint of every road is a farm. No two roads cross, and exactly one path links every pair of farms.
FJ lost his paper copy of the farm map and wants to rebuild it from backup data on his computer. The data has one line per road, such as:
- There is a road of length 10 running north from Farm #23 to Farm #17
- There is a road of length 7 running east from Farm #1 to Farm #17
- ...
While FJ retrieves the data, his navigationally challenged neighbor Farmer Bob sometimes interrupts with questions such as: What is the Manhattan distance between farms #1 and #23?
FJ answers Bob when he can. In the example above, the answer would be 17. The Manhattan distance between two points and is , which is the distance a taxi must travel over city streets in a perfect grid to connect the two points.
If FJ does not yet have enough information to deduce the distance between a pair of farms, he apologizes and replies with -1.
Input
The first line contains two space-separated integers and .
Lines 2 to each contain four space-separated entities , , , and that describe a road. and are the numbers of two farms connected by a road, is its length, and is one of the characters N, E, S, or W, giving the direction of the road from to .
Line contains a single integer (), the number of queries from Farmer Bob.
Lines to each contain three space-separated integers , , and . and are the numbers of the two farms in the query, and () is the data index after which Bob asks the query. Data index 1 is on line 2 of the input, and so on.
Output
For each of Bob's queries, print one integer on its own line: the Manhattan distance between the two farms as known after data index , or -1 if the distance cannot yet be determined.
Hint
At time 1, FJ knows the distance between 1 and 6 is 13. At time 3, the distance between 1 and 4 is still unknown. At the end, location 6 is 3 units west and 7 north of 2, so the distance is 10.