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 -*-
"""
Created on Sat Jul 14 19:11:44 2018

@author: maezawa
"""
infinity = 10**9

n = int(input())
m = []
for i in range(n):
    mi = list(map(int, input().split()))
    m.append(mi)

print(*m, sep='\n')

color = [0]*n
d = [10**9]*n
p = [0]*n
p[0] = -1
d[0] = 0

def prim():
    while True:
        mincost = 10**9
        for i in range(n):
            if color[i] != 2 and d[i] < mincost:
                mincost = d[i]
                u = i
        if mincost == 10**9:
            break

        color[u] = 2

        for v in range(n):
            if color[v] != 2 and m[u][v] != -1:
                if m[u][v] < d[v]:
                    d[v] = m[u][v]
                    p[v] = u
                    color[v] = 1
    sumw = 0
    for i in range(n):
        if p[i] != -1:
            sumw += m[i][p[i]]
    return sumw

print(prim())

Python: N = int(input())

#M[u][v]:uからvへの重みを保存した隣接行列
M=[]
for n in range(N):
    input_temp = list(map(int,input().split()))
    M.append(input_temp)

#color:各頂点の訪問状態を示す
color=['white']*N

#d:TとV-Tを繋ぐ辺の中で重みが最小の辺の重みの値を保持
d=[10**10]*N

#p[v-1]:MSTにおけるvの親を保持
p=[-1]*N

#初期値
d[0] = 0
p[0] = -1

# ans=0
while True:
#     ans+=1
    mincost=10**10
    for i in range(N):
        if color[i] != 'BLACK' and d[i] < mincost:
            mincost = d[i]
            u = i
#     print(u,mincost)       
    if mincost == 10**10:
        break
    
    color[u] = 'BLACK'
    
    for v in range(N):
        if color[v] != 'BLACK' and M[u][v]!=-1:
#             print(u,v,color[v],M[u][v],d[v])
            if M[u][v] < d[v]:
                d[v] = M[u][v]
                p[v] = u
                color[v] = 'GRAY'
#     print(color,mincost,d,p)
    
print(sum(d))

Python: # -*- coding: utf-8 -*-
def prim(edges, *, start=0, adj_matrix=False, default_value=float('inf')):
    '''
    Returns the Minimum Spanning Tree(MST) of a given graph

    # sample input when given not as adjacency list (generally works faster)
    edges = [[(1, 2), (2, 5), (3, 4)],         # node 0
             [(0, 2), (3, 3), (4, 6)],         # node 1
             [(0, 5), (3, 2), (5, 6)],         # node 2
             [(0, 4), (1, 3), (2, 2), (4, 2)], # node 3
             [(1, 6), (3, 2), (5, 4)],         # node 4
             [(2, 6), (4, 4)]]                 # node 5

    # sample input when given as adjacency matrix
    edges = [[0, 2, 5, 4, inf, inf],           # node 0
             [2, 0, inf, 3, 6, inf],           # node 1
             [5, inf, 0, 2, inf, 6],           # node 2
             [4, 3, 2, 0, 2, inf],             # node 3
             [inf, 6, inf, 2, 0, 4],           # node 4
             [inf, inf, 6, inf, 4, 0]]         # node 5
    '''

    n = len(edges)
    mst = []
    cost = 0
    T = [start]

    while True:
        tmp_edges = [(cost, (u, v)) for u in T for v, cost in enumerate(edges[u]) if cost != default_value and v not in T] if adj_matrix else\
                    [(cost, (u, v)) for u in T for v, cost in edges[u] if v not in T]

        if tmp_edges:
            min_cost, min_edge = min(tmp_edges)
            mst.append(min_edge)
            cost += min_cost
            T.append(min_edge[1])

        else:
            if len(mst) != n - 1:
                raise NoSpanningError(
                    'There is no spanning tree in this graph (search started from node{})'.
                    format(start))

            else:
                return mst, cost


class NoSpanningError(Exception):
    pass


if __name__ == '__main__':
    '''
    an example of using this function
    AIZU ONLINE JUDGE - ALDS_1_12_A
    '''

    n = int(input())
    edges = [[(j, int(cost)) for j, cost in enumerate(input().split()) if int(cost) != -1] for i in range(n)]

    print(prim(edges)[1])

Python: import sys
# sys.stdin = open('input.txt')

def createMatrix():
  matrix = [[i for i in map(int, input().split())] for i in range(n)]
  return matrix

def prim():
    d[0] = 0
    p[0] = -1

    while True:
        mincost = INFTY
        for i in range(n):
            if status[i] != VISITED and d[i] < mincost:
                mincost = d[i]
                u = i

        if mincost == INFTY:
            break

        status[u] = VISITED

        for v in range(n):
            if status[v] != VISITED and matrix[u][v] != -1:
                if matrix[u][v] < d[v]:
                    d[v] = matrix[u][v]
                    p[v] = u
                    status[v] = VISITING

n = int(input())
NOT_VISITED = 0 # WHITE
VISITING = 1 # GRAY
VISITED = 2 # BLACK
INFTY = 10**21

matrix = createMatrix()
status =  [NOT_VISITED] * n
d = [INFTY] * n
p = [-1] * n

prim()
print(sum(d))

Python: import heapq
from collections import defaultdict
v_num = int(input())
edges = defaultdict(list)
for i in range(v_num):
    data = [int(n) for n in input().split(" ")[1:]]
    for j in range(i + 1, v_num):
        if data[j] != -1:
            edges[i].append([data[j], j])
            edges[j].append([data[j], i])
queue = []
heapq.heapify(queue)
for c in edges[0]:
    heapq.heappush(queue, c)
visited = {0}
answer = 0
while len(visited) < v_num:
    q = heapq.heappop(queue)
    weight, one = q[0], q[1]
    if one in visited:
        continue
    answer += weight
    for e in edges[one]:
        heapq.heappush(queue, e)
    visited |= {one}
print(answer)

Python: n = int(input())
G = []
for i in range(n):
    G.append(input().split())
    for j in range(len(G[i])):
        G[i][j] = int(G[i][j])

ans = 0
mincost = [2001] * n
flag = [0] * n
mincost[0] = 0
while True:
    v = -1
    for j in range(n):
        if flag[j] != 1 and (v == -1 or mincost[j] < mincost[v]):
            v = j
    if v == -1:
        break
    flag[v] = 1
    ans += mincost[v]
    for j in range(n):
        if G[v][j] == -1: continue
        mincost[j] = min(mincost[j], G[v][j])

print(ans)