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)

class Vertex
  class << self
    def register(index, weights)
      @vertexes ||= {}
      @vertexes[index] = new(index, weights)
    end

    def find(index)
      @vertexes[index]
    end

    def each
      @vertexes.each { |_, v| yield v }
    end
  end

  attr_reader :index
  attr_accessor :parent

  def initialize(index, weights)
    @index = index
    @index_cost_map = weights.map.with_index { |e, i| e == -1 ? nil : [i, e] }.compact!.to_h
    @selected = false
  end

  def neighbors
    @neighbors ||= @index_cost_map.keys.map { |i| self.class.find(i) }
  end

  def neighbor?(other)
    @index_cost_map.key?(other.index)
  end

  def cost(other)
    @index_cost_map[other.index]
  end

  def selected?
    @selected
  end

  def select!
    @selected = true
  end
end

class Prim
  class << self
    def solve
      min_costs = Hash.new { |h, k| h[k] = Float::INFINITY }
      min_costs[0] = 0

      loop do
        min_cost = Float::INFINITY
        selected_vertex = nil
        Vertex.each do |v|
          if !v.selected? && min_costs[v.index] < min_cost
            selected_vertex = v
            min_cost = min_costs[v.index]
          end
        end

        break if selected_vertex.nil?

        selected_vertex.select!

        Vertex.each do |v|
          next if v.selected? || !selected_vertex.neighbor?(v)

          if selected_vertex.cost(v) < min_costs[v.index]
            min_costs[v.index] = selected_vertex.cost(v)
            v.parent = selected_vertex
          end
        end

      end

      sum = 0
      Vertex.each { |v| sum += v.parent.cost(v) if v.parent }
      sum
    end
  end
end

n = gets.to_i
n.times do |i|
  Vertex.register(i, gets.strip.split.map(&:to_i))
end

puts Prim.solve