Under construction

Still being built. Things may change

Construct a Graph

Interview

Time limit1sMemory limit1024 MB

Summary
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 N×NN\times N matrix DD. Build an undirected connected graph with NN vertices that satisfies the conditions below. Vertices are numbered from 1 to NN, and each edge can be given any positive integer weight.

  • For every pair of vertices (u,v)(u,v), the length of the shortest path between uu and vv is Du,vD_{u,v}.
  • 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 NN, the number of vertices. Each of the next NN lines contains NN integers separated by spaces. The ii-th of these lines contains Di,1,Di,2,…,Di,ND_{i,1}, D_{i,2}, \ldots, D_{i,N}.

Output

If no graph satisfies the conditions, print −1-1.

If such a graph exists, print the number of edges MM on the first line. On each of the next MM lines, print three integers uiu_i, viv_i, cic_i separated by spaces. This means that edge ii connects vertices uiu_i and viv_i and has weight cic_i.

At most one edge may connect any pair of vertices, and each edge weight must be at most 10910^9.

Constraints

  • 2≤N≤3002 \le N \le 300
  • Di,i=0D_{i,i}=0 (1≤i≤N1 \le i \le N)
  • 1≤Di,j=Dj,i≤1091 \le D_{i,j}=D_{j,i} \le 10^9 (1≤i<j≤N1 \le i < j \le N)
  • 1≤ui,vi≤N1 \le u_i, v_i \le N (1≤i≤M1 \le i \le M)
  • ui≠viu_i \neq v_i (1≤i≤M1 \le i \le M)
  • 1≤ci≤1091 \le c_i \le 10^9 (1≤i≤M1 \le i \le M)
  • At most one edge may connect any pair of vertices.

Examples2

  1. Example 1

    Input
    3
    0 1 2
    1 0 3
    2 3 0
    
    Expected output
    2
    1 2 1
    1 3 2
    
  2. Example 2

    Input
    3
    0 1 3
    1 0 1
    3 1 0
    
    Expected output
    -1