Construct a Graph
InterviewTime limit1sMemory limit1024 MB
Given an N x N distance matrix, build a connected weighted graph whose shortest-path distances match it with minimum total edge weight, or report -1 if none exists.
- Level
Medium5 of 10
- Topics
- Graph, Shortest path
- Solved
- No attempts yet
Statement
You are given an matrix . Build an undirected connected graph with vertices that satisfies the conditions below. Vertices are numbered from 1 to , and each edge can be given any positive integer weight.
- For every pair of vertices , the length of the shortest path between and is .
- The sum of all edge weights must be as small as possible.
Determine whether such a graph exists. If it does, print any one of them.
Input
The first line contains the integer , the number of vertices. Each of the next lines contains integers separated by spaces. The -th of these lines contains .
Output
If no graph satisfies the conditions, print .
If such a graph exists, print the number of edges on the first line. On each of the next lines, print three integers , , separated by spaces. This means that edge connects vertices and and has weight .
At most one edge may connect any pair of vertices, and each edge weight must be at most .
Constraints
- ()
- ()
- ()
- ()
- ()
- At most one edge may connect any pair of vertices.