Go: package main

import (
	"bufio"
	"fmt"
	"log"
	"math"
	"os"
	"strconv"
	"strings"
)

type color int

const (
	white color = iota // 未訪問
	mst                // MSTとして確定
)

// 頂点
type node struct {
	matrix   []int // 隣接行列
	minToMst int   // MSTへの重み最小値
	parent   int   // 最小値の相手
	color    color
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	n := eGetInt(scanner)

	nodes := make([]node, n)
	for i := 0; i < n; i++ {
		nodes[i].matrix = eAtoi((strings.Fields(eGetline(scanner))))
		nodes[i].parent = -1
		nodes[i].minToMst = math.MaxInt16
		nodes[i].color = white
	}

	// 初回はnode[0]がMSTに入るように,minToMstを設定
	nodes[0].minToMst = 0
	for { // 全部チェックするまで

		// どの頂点を新たにMSTに取り込むか
		min := math.MaxInt16
		u := -1
		for i := 0; i < n; i++ {
			if nodes[i].color == mst {
				continue
			}
			if nodes[i].minToMst < min {
				u = i
				min = nodes[i].minToMst
			}
		}

		if u == -1 {
			break
		}
		// MSTに追加する頂点決定
		nodes[u].color = mst

		// MSTに属していない頂点それぞれについて,MSTとの最小の重みを更新
		for i := 0; i < n; i++ {
			if nodes[i].color == mst {
				continue
			}
			if nodes[i].matrix[u] == -1 {
				// 接してない
				continue
			}
			if nodes[i].matrix[u] < nodes[i].minToMst {
				// node[u]との重みが最小
				nodes[i].minToMst = nodes[i].matrix[u]
				nodes[i].parent = u
			}
		}
	}

	sum := 0
	for _, v := range nodes {
		// node[0]はparentが入っていない
		if v.parent != -1 {
			sum += v.matrix[v.parent]
		}
	}
	fmt.Println(sum)
}

func eGetInt(scanner *bufio.Scanner) int {
	t := eAtoi(strings.Fields(eGetline(scanner)))
	return t[0]
}

func eGetline(p *bufio.Scanner) string {
	if !p.Scan() {
		if err := p.Err(); err != nil {
			log.Fatal(err.Error())
		}
		return ""
	}
	return p.Text()
}

func eAtoi(s []string) []int {
	ints := make([]int, len(s))
	var err error
	for i, e := range s {
		ints[i], err = strconv.Atoi(e)
		if err != nil {
			log.Fatal(err.Error())
		}
	}
	return ints
}

Python: # -*- coding: utf-8 -*-

"""Minimum Spanning Tree"""

import sys
import os
import pprint

DEBUG = False

#fd = os.open('ALDS1_12_A.txt', os.O_RDONLY)
#os.dup2(fd, sys.stdin.fileno())

n = int(input())

# n x n matrix
M = []
for i in range(n):
    l = list(map(int, input().split()))
    M.append(l)

# Prim's Algorithm
INF = 1000000
visited = [False] * n
parent = [None] * n

# 0 is in T (Tree)
parent[0] = None

# distance between T and T-V
distance = [INF] * n
distance[0] = 0

while True:
    min_dist = INF
    candidate_index = None
    for i in range(n):
        if not visited[i] and distance[i] < min_dist:
            min_dist = distance[i]
            candidate_index = i

    if candidate_index is None:
        break

    if DEBUG:
        print('accepted i', candidate_index)
    visited[candidate_index] = True
    distance[candidate_index] = -1  # done

    for i in range(n):
        if not visited[i] and M[candidate_index][i] != -1 and distance[i] > M[candidate_index][i]:
            distance[i] = M[candidate_index][i]
            parent[i] = candidate_index


# Trees length
_sum = 0
for i in range(n):
    if parent[i] is not None:
        d = M[i][parent[i]]
        _sum += d
print(_sum)

Python: n=int(input())
matrix=[list(map(int,input().split())) for _ in range(n)]
weight=[]
for x in range(n):
    for y in range(x,n):
        if matrix[x][y]>=0: weight.append((x,y,matrix[x][y]))
weight.sort(key=lambda x:x[2])
ans=0
p=[i for i in range(n)]

def root(x):
    path_to_root=[]
    while p[x]!=x:
        path_to_root.append(x)
        x=p[x]
    for node in path_to_root:
        p[node]=x
    return x
    
def is_same_set(x,y):
    return root(x)==root(y)
    
def unite(x,y):
    p[root(x)]=root(y)
        
for x,y,w in weight:
    if not is_same_set(x,y):
        unite(x,y)
        ans+=w
print(ans)

Python: n = int(input())
edgeList = []
for i in range(n):
    a = list(map(int, input().split()))
    for j in range(i):
        if a[j] != -1:
            edgeList.append([a[j], getRoot(i), getRoot(j)])
rootList = [-1 for i in range(n)]
sumLength = 0

def getRoot(x):
    r = rootList[x]
    if r < 0:
        rootList[x] = x
    elif r != x:
        rootList[x] = getRoot(r)
    return rootList[x]
        

edgeList.sort(key=lambda x: x[0])
for e in edgeList:
    x = getRoot(e[1])
    y = getRoot(e[2])
    if x != y:
        sumLength += e[0]
        rootList[x] = rootList[y] = min(x, y)
print(sumLength)

Python: n = int(raw_input())
a = []

for i in range(n):
    inp = raw_input()
    if "-1" in inp:
        inp = inp.replace("-1","10000")
    a.append(list(map(int, inp.split())))

w = 0
v = set()
v.add(0)

while len(v) < n:
    min_w   = 10000
    min_idx = 0
    i = 0
    for node in v:
        if min_w > min(a[node]):
            min_w = min(a[node])
            i = node
            min_idx = a[i].index(min_w)
    if min_idx in v:
        a[i][min_idx] = 10000
        continue
    else:
        w += min_w
        v.add(min_idx)

print(w)

Python: n=int(input())
M=[list(map(int,input().split()))for _ in[0]*n]
d=[0]+[1e4]*n
b=[1]*n
a=0
while 1:
 u=-1
 for i in range(n):
  if b[i]and(u<0 or d[i]<d[u]):u=i
 if u<0:break
 b[u]=0
 a+=d[u]
 for v in range(n):
  t=M[u][v]
  if t+1 and d[v]>t:d[v]=t
print(a)

Python: def prim(n,M):
    d = [None]*n
    p = [None]*n
    searched = [0]*n
    
    for i in range(n):
        d[i] = float("inf")
        p[i] = -1
    
    d[0] = 0
    
    while True:
        minv = float("inf")
        u = -1
        for i in range(n):
            if minv > d[i] and not searched[i]:
                u = i
                minv = d[i]
        
        if u == -1:
            break
        searched[u] = 1
        for v in range(n):
            if (not searched[v]) and M[u][v] != -1:
                if d[v] > M[u][v]:
                    d[v] = M[u][v]
                    p[v] = u

    s = 0
    for i in range(n):
        if p[i] != -1:
            s += M[i][p[i]]
    return print(s)

n = int(input())
M = [list(map(int,input().split())) for _ in range(n)]
prim(n,M)

Python: #!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys

WHITE, GRAY, BLACK = 0, 1, 2


def prim_span_tree():
    min_weight_vertices[0] = 0

    while True:
        min_cost = 2001
        current_vertex = -1
        for i in range(vertices_num):
            if color[i] != BLACK and min_weight_vertices[i] < min_cost:
                min_cost = min_weight_vertices[i]
                current_vertex = i

        if min_cost == 2001:
            break

        color[current_vertex] = BLACK

        for j in range(vertices_num):
            v_weight = int(init_vertices_matrix[current_vertex][j])
            if color[j] != BLACK and v_weight >= 0:
                if v_weight < min_weight_vertices[j]:
                    min_weight_vertices[j] = v_weight
                    parent_list[j] = current_vertex
                    color[j] = GRAY

    return min_weight_vertices


if __name__ == '__main__':
    _input = sys.stdin.readlines()
    vertices_num = int(_input[0])
    init_vertices_matrix = list(map(lambda x: x.split(), _input[1:]))

    parent_list, min_weight_vertices = [-1] * vertices_num, [2001] * vertices_num
    color = [WHITE] * vertices_num
    ans = prim_span_tree()
    print(sum(ans))

Python: 
def prim(cost):
    sumcost = 0
    V = len(cost)
    mincost = [float('inf')] * V
    used = [False] * V
    mincost[0] = 0
    while True:
        j = -1
        for i in range(V):
            if not used[i] and (j == -1 or mincost[i] < mincost[j]):
                j = i
        if j == -1:
            break
        used[j] = True
        sumcost = sumcost + mincost[j]
        for i in range(V):
            if cost[i][j] == -1:
                continue
            mincost[i] = min(mincost[i], cost[j][i])
    return sumcost

n = int(raw_input())
A = [0] * n
for i in range(n):
    A[i] = map(int, raw_input().split())

result = prim(A)
print(result)