Cow Marathon
Time limit1sMemory limit1024 MB
Find the longest road distance between any two farms in a network where each road has a length.
Problem
Farmer John wants his cows to get more exercise after hearing about the obesity epidemic in the USA, so he has committed to create a bovine marathon for his cows to run. The marathon route will include a pair of farms and a path comprised of a sequence of roads between them. Since FJ wants the cows to get as much exercise as possible, he wants to find the two farms on his map that are the farthest apart from each other. Distance is measured as the total length of road on the path between the two farms. Help him determine the distance between this farthest pair of farms.
Input
- Line 1: Two space-separated integers: N and M
- Lines 2..M+1: Each line contains four space-separated entities, F1, F2, L, and D, that describe a road. F1 and F2 are the numbers of two farms connected by a road, L is its length, and D is a character that is either 'N', 'E', 'S', or 'W' giving the direction of the road from F1 to F2.
- Line M+2: A single integer K (1 ≤ K ≤ 10,000), the number of queries from Farmer Bob.
- Lines M+3..M+K+2: Each line corresponds to a query from Farmer Bob and contains three space-separated integers: F1, F2, and I. F1 and F2 are the numbers of the two farms in the query, and I (1 ≤ I ≤ M) is the data index after which Bob asks the query. Data index 1 is on line 2 of the input data, and so on.
Output
Line 1: An integer giving the distance between the farthest pair of farms.
Hint
The longest marathon runs from farm 2 via roads 4, 1, 6 and 3 to farm 5 and is of length 20+3+13+9+7=52.