All Roads Lead to Rome
Time limit1sMemory limit128 MB
Given a connected weighted graph, choose two hub nodes and assign every node to a hub to minimize the total routed distance over all ordered pairs.
- Level
Medium7 of 10
- Topics
- Graph, Shortest path, Greedy, Brute force
- Solved
- No attempts yet
Problem
A city is represented as a set of locations (nodes) connected by road segments (edges). A friend of mine drives around town in an unusual way that, he claims, cuts down the number of routes he has to memorize. First he picks two distinct locations to serve as hubs, and . He then assigns every other location to either or , and memorizes only the shortest path from each location to its assigned hub, plus the shortest path between the two hubs. (Each hub is considered assigned to itself.)
When he travels from location to location , the length of his route is defined as follows. Let be the hub that location is assigned to, and let be the shortest distance between and in the road network.
- If :
- If :
In other words, he always visits his own hub first; if the destination's hub is different, he travels to that hub and then to the destination.
You may choose the two hubs and the assignment of the remaining locations freely. Minimize the total route length summed over every ordered pair of distinct locations . (Because the number of locations is fixed, minimizing this total is the same as minimizing the average trip distance.) Output that minimum total.
Input
The first line of input contains the number of test cases .
Each test case begins with a line containing two integers and (, ), where is the number of locations and is the number of road segments directly connecting two locations. There may be more than one road segment between a pair of locations, and a road segment may start and end at the same location.
Each of the next lines contains three integers , , and (, , ), meaning the road segment between locations and has length . Every road is bidirectional.
A path along the road segments always exists between any two locations.
Output
For each test case, output a single line with one integer: the minimum possible total route length summed over every ordered pair of distinct locations , minimized over all choices of the two hubs and all assignments of the remaining locations to a hub.