Chocolate Giving
Time limit1sMemory limit128 MB
For each of B queries on a weighted undirected graph, output the shortest distance from pasture P to pasture Q that passes through the barn at pasture 1.
- Level
Medium5 of 10
- Topics
- Graph, Shortest path, Heap, Implementation
- Solved
- No attempts yet
Problem
The farmer is handing out chocolates at the barn for Valentine's Day. () bulls each have a special cow in mind to receive a chocolate gift.
Each bull and cow grazes alone in one of the farm's () pastures, numbered through and connected by () bidirectional cowpaths of various lengths. Two pastures may be directly connected by more than one cowpath. Cowpath connects pastures and (; ) and has length ().
Bull lives in pasture () and wants to give a chocolate to the cow in pasture ().
Help each bull find the shortest route from its own pasture to the barn (located at pasture ) and then onward to the pasture where its special cow grazes. The barn is connected -- directly or indirectly -- to every pasture.
For example, consider a farm with 6 pastures, 7 cowpaths, and 3 bulls (in pastures 2, 3, and 5) who each want to deliver a chocolate:
*1 <-- this bull wants to gift the cow in pasture 1
[4]--3--[5] <-- [5] is the pasture ID
/ |
/ |
4 2 <-- 2 is the length of the cowpath
/ | between [3] and [4]
[1]--1--[3]*6
/ \ /
9 3 2
/ \/
[6] [2]*4
The bull in pasture 2 can travel distance 3 to reach the barn, then distance 2 + 1 to pastures 3 and 4, for a total of 6.
The bull in pasture 5 can travel to pasture 4 (distance 3), then on to pastures 3 and 1 (3 + 2 + 1 = 6).
The bull in pasture 3 can travel distance 1 to pasture 1, then carry the chocolate 9 more to pasture 6, for a total distance of 10.
Input
- Line 1: three space-separated integers , , and .
- Lines 2 to : line describes cowpath with three space-separated integers , , and .
- Lines to : line contains two space-separated integers and .
Output
- Lines 1 to : line contains a single integer, the smallest total distance the bull in pasture must travel to pick up a chocolate at the barn and then deliver it to the cow of his dreams in pasture .