Best Spot
InterviewTime limit1sMemory limit128 MB
Given a weighted undirected graph and a set of favorite vertices, find the vertex whose average shortest-path distance to all favorites is smallest, breaking ties by smallest index.
- Level
Medium5 of 10
- Topics
- Graph, Shortest path, Heap, Brute force
- Solved
- No attempts yet
Problem
Bessie, always looking to optimize her life, has realized that she especially enjoys visiting her favorite pastures (, ) among the pastures (; conveniently numbered through ) that make up Farmer John's holdings.
The farm has bidirectional cowpaths (; conveniently numbered through ) connecting various pastures, and using them Bessie can travel to any pasture on the farm. The -th cowpath connects the two endpoints and (, ) and takes time () to traverse in either direction.
Bessie wants to find the number of the best pasture to sleep in, so that when she wakes up the average time to travel to each of her favorite pastures is minimized.
The map below shows an example farm. A pasture whose number is marked with an asterisk * is one of Bessie's favorites, and the number in brackets [] is the time to traverse that cowpath.
1*--[4]--2--[2]--3
| |
[3] [4]
| |
4--[3]--5--[1]---6---[6]---7--[7]--8*
| | | |
[3] [2] [1] [3]
| | | |
13* 9--[3]--10*--[1]--11*--[3]--12*
The following table shows, for each candidate "best pasture" , the distance to every favorite pasture and the resulting average.
* * * * * * Favorites * * * * * *
Potential Pasture Pasture Pasture Pasture Pasture Pasture Average
Best Pasture 1 8 10 11 12 13 Distance
------------ -- -- -- -- -- -- -----------
4 7 16 5 6 9 3 46/6 = 7.67
5 10 13 2 3 6 6 40/6 = 6.67
6 11 12 1 2 5 7 38/6 = 6.33
7 16 7 4 3 6 12 48/6 = 8.00
9 12 14 3 4 7 8 48/6 = 8.00
10 12 11 0 1 4 8 36/6 = 6.00 ** BEST
11 13 10 1 0 3 9 36/6 = 6.00
12 16 13 4 3 0 12 48/6 = 8.00
Assuming these candidates really are the best options (a program must check all pastures somehow), the best place to sleep is pasture , which has the smallest average distance.
Input
- Line 1: Three space-separated integers , , and .
- Next lines: Each line contains a single integer , the number of one of Bessie's favorite pastures.
- Next lines: Each line describes one cowpath with three space-separated integers , , and .
Output
- Print a single integer on one line: the number of the best pasture to sleep in. If more than one pasture is best, print the smallest such number.