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: MAX = 100
INF = 1 << 21
WHITE = 0 # ?????¢?´¢
GRAY = 1  # ??¢?´¢????±?
BLACK = 2 # ??¢?´¢??????

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

for i in range(n):
    for j in range(n):
        if M[i][j] == -1:
            M[i][j] = INF

d = [INF for i in range(n)] # ??¢?´¢????±?
p = [-1 for i in range(n)]  # ??????????????????
color = [WHITE for i in range(n)]

def prim():
    global M, d, p, color

    d[0] = 0

    while(1):
        minv, u = INF, -1
        for i in range(n):
            if minv > d[i] and color[i] != BLACK:
                u = i
                minv = d[i]
        if u == -1:
            break
        color[u] = BLACK # ??¢?´¢???????????´??°
        for v in range(n):
            if color[v] != BLACK and M[u][v] != INF:
                if d[v] > M[u][v]:
                    d[v], p[v], color[v] = M[u][v], u, GRAY
    return sum([M[i][p[i]] for i in range(n) if p[i] != -1])


print(prim())

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

Python: N = int(input())
P = [i for i in range(N)]
weight = []

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)
    
# まずは辺の重さをソートするために辺の重さの配列を作りましょう→マイナス1は除外
for i in range(N):
    lis = list(map(int,input().split()))
    for j in range(N):
        if lis[j] == -1:
            continue
        else:
            weight.append([lis[j],i,j])
# ソートされた順に小さい順から次々とuniteして行こう
weight.sort()
length = len(weight)
k = 0
total_weight = 0

for k in range(length):
    if is_same_set(weight[k][1],weight[k][2]):
        continue
    else:
        unite(weight[k][1],weight[k][2])
        total_weight += weight[k][0]

print(total_weight)
    
# その際にもし付け加えてis_same_set(x,y)がtrueだったらやめよう

Python: infinity = float('inf')
n = int(input())
a = []

for i in range(n):

    line = list(map(int, input().split()))

    for i in range(len(line)):
        if line[i] == -1:
            line[i] = infinity
    a.append(line)

checked = [False] * n
d = [infinity] * n
checked[0] = True
ansswer = 0
next = 0

for i in range(n - 1):
    for j in range(n):
        if a[next][j] < d[j]:
            d[j] = a[next][j]

    minimumNeightbor = 0
    minimumWeight = infinity

    for j in range(n):
        if not checked[j] and d[j] < minimumWeight:
            minimumNeightbor = j
            minimumWeight = d[j]

    checked[minimumNeightbor] = True
    next = minimumNeightbor
    ansswer += minimumWeight

print(ansswer)

Python: INF = float("inf")
def MAIN():
    n = int(input())
    M = [[INF] * 101 for _ in range(101)]
    for i in range(n):
        for j, e in enumerate(map(int, input().split())):
            if e != -1:
                M[i][j] = e
    def prim():
        d = [INF] * n
        t = [-1] * n
        color = [0] * n
        d[0] = 0
        while True:
            minv = INF
            u = -1
            for i in range(n):
                if minv > d[i] and color[i] != 2:
                    u = i
                    minv = d[i]
            if u == -1:
                break
            color[u] = 2
            for v in range(n):
                if color[v] != 2 and d[v] > M[u][v]:
                    d[v] = M[u][v]
                    t[v] = u
                    color[v] = 1
        return sum(d)
    print(prim())
MAIN()

Python: # minimum_spanning_tree
def prim(adj_matrix, n):
    dist = [float("inf") for _ in range(n)]  # 訪問確定したノードからの最短距離
    visited = [False for _ in range(n)]  # ノードの訪問が確定したか
    parent = [-1 for _ in range(n)]  # start -> endを保存するためのstart？
    cost = 0
    inf = float("inf")

    start = 0
    visited[start] = True
    dist[start] = 0
    while True:
        # startから直接つながっている未訪問ノードをもとに、距離の最小値を更新する
        for end in range(n):
            if not visited[end] and adj_matrix[start][end] > -1 and adj_matrix[start][end] < dist[end]:
                dist[end] = adj_matrix[start][end]
                parent[end] = start

        min_cost = inf
        for nextnode in range(n):
            # dist_nodeの中から最もコストの短いノードを探す。そのノードは訪問確定。それを次回のstartとする。
            if not visited[nextnode] and dist[nextnode] < min_cost:
                min_cost = dist[nextnode]
                start = nextnode
        if min_cost == inf:
            break

        visited[start] = True
        cost += min_cost

    return parent, cost


def main():
    n = int(input())
    adj_matrix = []
    for _ in range(n):
        row = input().split()
        adj_matrix.append(list(map(int, row)))
    parent, cost = prim(adj_matrix, n)
    print(cost)


if __name__ == "__main__":
    main()

Python: n = int(input())
M = [[float("inf") for i in range(n)] for i in range(n)]
for i in range(n):
 L = list(map(int, input().split()))
 for j,v in enumerate(L):
  if v != -1:
   M[i][j] = v

def prim():
 color = [0] * n
 d = [float("inf")] * n
 p = [-1] * n
 d[0] = 0

 while True:
  minv = float("inf")
  u = -1
  for i in range(n):
   if minv > d[i] and color[i] != 2:
    u = i
    minv = d[i]
  if u == -1: break
  color[u] = 2
  for v in range(n):
   if color[v] != 2 and M[u][v] != float("inf"):
    if d[v] > M[u][v]:
     d[v] = M[u][v]
     p[v] = u
     color[v] = 1
 sum = 0
 for i in range(n):
  if p[i] != -1:
   sum += M[i][p[i]]
 return str(sum)

print(prim())