Neighbouring Towns
Time limit1sMemory limit128 MB
Given a symmetric shortest-distance table for n towns, list every pair A,B such that no third town C satisfies dist(A,B) = dist(A,C) + dist(C,B).
- Level
Medium4 of 10
- Topics
- Array, Brute force
- Solved
- No attempts yet
Problem
A road map comes with a table that gives, for every pair of towns, the length of the shortest route between them. All roads are two-way, so the table is symmetric, and the distance from a town to itself is .
The towns have a special property: whenever the shortest distance from town to town equals the shortest distance from to plus the shortest distance from to , some shortest route from to passes through town .
Two towns and are called neighbouring towns when no other town lies between them on a shortest route, that is, when there is no town (different from and ) for which
Given the distance table, find every pair of neighbouring towns.
Your program reads the table of distances from standard input, finds all pairs of neighbouring towns, and writes them to standard output.
Input
The first line contains an integer (), the number of towns; the towns are numbered from to .
Each of the next lines contains non-negative integers no greater than , separated by single spaces. The -th integer on the -th of these lines is the shortest distance between town and town . The diagonal entries are and the table is symmetric.
Output
Print every pair of neighbouring towns, one pair per line. Within a pair, print the two town numbers in increasing order, separated by a single space. List each pair only once.
Order the lines so that a pair comes before a pair when , or when and .
If there are no neighbouring pairs, print nothing.