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)

def mst ms, n
  colors = Array.new(n){1} # 1:white, 2:gray, 3:black
  costs = Array.new(n){Float::INFINITY}
  sums = 0

  colors[0] = 2
  costs[0] = 0

  while true do
    min_cost = Float::INFINITY
    min_cost_i = nil
    costs.each_with_index do |cost, i|
      if colors[i] == 2 && cost < min_cost
        min_cost = cost
        min_cost_i = i
      end
    end

    break if min_cost_i.nil?

    colors[min_cost_i] = 3
    sums += min_cost

    colors.each_with_index do |color, i|
      if color == 3
        ms[i].each_with_index do |m, j|
          if colors[j] != 3 && m < costs[j]
            costs[j] = m
            colors[j] = 2
          end
        end
      end
    end
  end

  sums
end

n = gets.chomp.to_i
ms = Array.new(n)
n.times do |i|
  ms[i] = gets.chomp.strip.split(' ').map(&:to_i).map{|x| x == -1 ? Float::INFINITY : x}
end
puts mst(ms, n)