Problem:
MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Minimum Spanning Tree

For a given weighted graph $G = (V, E)$, find the minimum spanning tree (MST) of $G$ and print total weight of edges belong to the MST.

Input

In the first line, an integer $n$ denoting the number of vertices in $G$ is given. In the following $n$ lines, a $n \times n$ adjacency matrix $A$ which represents $G$ is given.
$a_{ij}$ denotes the weight of edge connecting vertex $i$ and vertex $j$. If there is no edge between $i$ and $j$, $a_{ij}$ is given by -1.

Output

Print the total weight of the minimum spanning tree of $G$.

Constraints

$1 \leq n \leq 100$

$0 \leq a_{ij} \leq 2,000$ (if $a_{ij} \neq -1$)

$a_{ij} = a_{ji}$

$G$ is a connected graph

Sample Input 1

5
-1 2 3 1 -1
2 -1 -1 4 -1
3 -1 -1 1 1
1 4 1 -1 3
-1 -1 1 3 -1

Sample Output 1

5

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.

Solution in Ruby (judge verdict: Accepted)

  module Color
  WHITE = 0
  GRAY = 1
  BLACK = 2
end

def prim()
  d = Array.new($n, Float::INFINITY)
  color = Array.new($n, Color::WHITE)
  p = Array.new($n, -1)
  
  d[0] = 0

  while true
    mincost = Float::INFINITY
    u = nil
    $n.times do |i|
      if color[i] != Color::BLACK && d[i] < mincost
        mincost = d[i]
        u = i
      end
    end

    if mincost == Float::INFINITY
      break
    end

    color[u] = Color::BLACK

    $n.times do |v|
      if color[v] != Color::BLACK && $m[u][v] != Float::INFINITY
        if $m[u][v] < d[v]
          d[v] = $m[u][v]
          p[v] = u
          color[v] = Color::GRAY
        end
      end
    end
  end
  sum = 0
  $n.times do |i|
    if p[i] !=- 1
      sum += $m[i][p[i]]
    end
  end
  sum
end

$n = gets.to_i
$m = Array.new($n) { Array.new($n) }
$n.times do |i|
  arr = gets.split.map(&:to_i)
  $n.times do |j|
    $m[i][j] = arr[j] == -1 ? Float::INFINITY : arr[j]
  end
end
puts prim()