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 Python (judge verdict: Wrong Answer)

n = input()
 
INF = 10000000
 
color = [0 for i in xrange(n)]
M = [[INF for i in xrange(n)] for i in xrange(n)]
d = [INF for i in xrange(n)]
p = [-1 for i in xrange(n)]
 
def m_s_t():
  d[0] = 0
 
  while True:
    cost = INF
    for i in xrange(n):
      if color[i] != 2 and d[i] < cost:
        cost = d[i]
        u = i
 
    if cost == INF:
      break
     
    color[u] = 2
   
  for v in xrange(n):
     if color[v] != 2 and M[u][v] != INF and M[u][v] < d[v]:
        d[v] = M[u][v]
        p[v] = u
        color[v] = 1
 
  sum = 0
  for i in xrange(n):
    if p[i] != -1:
      sum += M[i][p[i]]
  return sum
 
for i in xrange(n):
  G = map(int, raw_input().split())
  for j in range(n):
   if G[j] != -1:
     M[i][j] = G[j]
 
print m_s_t()