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 Priority_queue
  def initialize(bool = true)
    if bool
      @ope = proc{|a, b|(a and b)? a > b : false}
    else
      @ope = proc{|a, b|(a and b)? a < b : false}
    end
    @heap = []
  end

  def <<(other)
    @heap.push(other)
    up
  end

  def gets
    result = @heap.shift
    @heap.unshift(@heap.pop)
    down
    return result
  end
  
  def up(key = @heap.size - 1)
    if @ope.call(@heap[key / 2], @heap[key])
      @heap[key / 2], @heap[key] = @heap[key], @heap[key / 2]
      down(key / 2)
      up(key / 2)
    end
  end

  def down(key = 0)
    if @ope.call(@heap[key], @heap[key * 2]) and @ope.call(@heap[key * 2 + 1], @heap[key * 2])
      @heap[key], @heap[key * 2] = @heap[key * 2], @heap[key]
      down(key * 2)
    elsif @ope.call(@heap[key], @heap[key * 2 + 1])
      @heap[key], @heap[key * 2 + 1] = @heap[key * 2 + 1], @heap[key]
      down(key * 2 + 1)
    end
  end
  def inspect
    @heap
  end
  
end
class Edge
  include Comparable
  attr_reader :cost
  def initialize(a, b, cost)
    @a, @b = a, b
    @cost = cost
  end
  def self.set(n)
    @@array = Array.new(n, false)
  end
  def self.reach(n)
    @@array[n] = true
  end
  def <=>(other)
    @cost <=> other.cost
  end
  def reach?
    @@array[@a] and @@array[@b]
  end
  def to
    return @b
  end
  def inspect
    "|#{@a}<#{@cost}>#{@b}|"
  end
end

def main
  n = gets.to_i
  Edge::set(n)
  matrix = []
  n.times do
    matrix << gets.split(" ").map(&:to_i)
  end
  counter = 0
  position = 0
  queue = Priority_queue.new
  cost = 0
  while counter < n
    Edge::reach(position)
    matrix[position].each_with_index{|item, idx|
      queue << Edge.new(position, idx, item) if item != -1
    }
    minimum = queue.gets
    while minimum and minimum.reach?
      minimum = queue.gets
    end
    cost += minimum.cost if minimum
    position = minimum.to if minimum
    counter += 1
  end
  puts cost
end

main