Absurdistan Roads
Time limit5sMemory limit128 MB
Given all-pairs shortest distances, find the minimum total length of a connected N-edge road network that reproduces the table.
- Level
Hard8 of 10
- Topics
- Minimum spanning tree, Graph, Shortest path
- Solved
- No attempts yet
Problem
The people of Absurdistan worked out how to build roads only last year. Every one of the cities then built exactly one road from itself to another city, and every road can be travelled in both directions. Each road has an integer length between 1 and 1,000,000. Two cities can end up joined by two roads, but no road joins a city to itself.
The work took all cities precisely one year, and once it was finished, every city could reach every other city over the new roads.
Your tourist guide has no map of the new roads. It only prints a table with the shortest travelling distance between every pair of cities. Several different networks of roads can produce the same table. Given the table, find the smallest possible total length of the roads.
Input
The input holds several test cases and ends at the end of the file.
Each test case starts with a line holding an integer (), the number of cities, which is also the number of roads. The next lines hold integers each. The -th integer on the -th line is the shortest distance from city to city . The distance from to is 0, the distance from to equals the distance from to , and every distance between two distinct cities is positive and at most 1,000,000. At least one network of roads matches the table.
Output
For each test case, print one line with the smallest possible total length of the roads.