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: n = int(input())

adj = [list(map(int, input().split())) for i in range(n)]

def mst():
    T = [0]
    gross_weight = 0
    cnt = n - 1
    while cnt:
        ew = 2001
        for i in range(len(T)):
            for tv, tew in enumerate(adj[T[i]]):
                if (tv not in T) and (tew != -1):
                    if tew < ew:
                        v, ew = tv, tew
        T.append(v)
        gross_weight += ew
        cnt -= 1
    print(gross_weight)


mst()

Python: from collections import deque

class Node:
    def __init__(self, val):
        self.val = val
        self.child = []

n = int(input())
g = []
# mst = [[] for _ in range(n)]
# mst = [None for _ in range(n)]

for i in range(n):
    g.append(list(map(int, input().split())))

# print(g)

for i in range(n):
    for j in range(n):
        if g[i][j] == -1:
            g[i][j] = 10**5

mst = Node(0)
# done = set()

def getClosestVertex(done):
    w = 10**10
    closest = None
    for i in done:
        for j in range(len(g[i])):
            if j in done:
                continue
            if g[i][j] < w:
                w = g[i][j]
                closest = j
    return closest, w

done = set()
done.add(0)
ans = 0

while True:
    closest, w = getClosestVertex(done)
    if closest is None:
        break
    else:
        done.add(closest)
        ans += w

print(ans)

Python: from sys import stdin
INF = 1<<21
WHITE, GRAY, BLACK = 0, 1, 2
n = int(stdin.readline())
M = [[INF] * n for _ in range(n)]
for i in range(0, n):
    for j, e in enumerate(list(map(int, stdin.readline().split()))):
        if e != -1: M[i][j] = e
d = [INF] * n
d[0] = 0
color = [False] * n
def prim():
    while True:
        minv = INF
        u = -1
        for i in range(0, n):
            if minv > d[i] and color[i] != True:
                u = i
                minv = d[i]
        if u == -1: break
        color[u] = True
        for v in range(0, n):
            if color[v] != True and d[v] > M[u][v]:
                d[v] = M[u][v]
    return sum(d)
print(prim())

Python: #coding:utf-8
inf = 1000000
n = int(input())
mtrx = []
for i in range(n):
    nums = list(map(int,input().split()))
    col = []
    for j in range(n):
        if nums[j] == -1:
            col.append(inf)
        else:
            col.append(nums[j])
    mtrx.append(col)

        
d = [inf for i in range(n)]
p = [-1 for i in range(n)]
color = ["white" for i in range(n)]
d[0] = 0
while True:
    mincost = inf
    for i in range(n):
        if color[i] != "black" and d[i] < mincost:
            mincost = d[i]
            u = i
    if mincost == inf:
        break

    color[u] = "black"
    for v in range(n):
        if color[v] != "black" and mtrx[u][v] < inf:
            if mtrx[u][v] < d[v]:
                d[v] = mtrx[u][v]
                p[v] = u
                color[v] = "gray"
print(sum(d))

Python: n = int(input())
sides = []
ws = []
ss = []
for _ in range(n):
    sides.append(list(map(int,input().split())))
for i in range(n):
    for j in range(i+1,n):
        if sides[i][j] >= 0:
            ws.append([sides[i][j],i,j])
rs = [(i) for i in range(n)]
def root(x):
    global rs
    if rs[x] == x:
        return(x)
    else:
        return(root(rs[x]))
ws.sort()
ans = 0
while(len(ws)):
    if root(ws[0][1]) != root(ws[0][2]):
        ans += ws[0][0]
        rs[root(rs[ws[0][2]])] = root(ws[0][1])
        ss.append(ws[0])
    del(ws[0])
print(ans)

Python: import heapq

def make_adj_list(v):
    adj_list = [[-1 for i in range(v)] for j in range(v)]
    return adj_list

def prim(adj_list, v, s):
    # スタートを0とする
    min_d = 0
    heap = []
    used = []
    for i in range(v):
        used.append(False)
    used[s] = True
    for i in range(v):
        if adj_list[s][i] != -1:
            heapq.heappush(heap, (adj_list[s][i], i))
        #　スタートからつなぐことができる辺をheapに入れる

    while len(heap) != 0:
        cost, to = heapq.heappop(heap)
        if used[to]:
            continue
        min_d += cost
        used[to] = True
        for i in range(v):
            if adj_list[to][i] != -1:
                heapq.heappush(heap, (adj_list[to][i], i)) 
            #集合に入れた頂点からつなぐことができる辺をheapに入れる

    return min_d

def main():
    v = int(input())
    adj_list = make_adj_list(v)
    for i in range(v):
        adj_list[i] = [int(j) for j in input().split()]
    min_d = prim(adj_list, v, 0)
    print(min_d)


if __name__ == '__main__':
    main()