Go: package main

import (
	"bufio"
	"fmt"
	"os"
	"sort"
	"strconv"
)

var scanner = bufio.NewScanner(os.Stdin)

func nextString() string {
	scanner.Scan()
	return scanner.Text()
}

func nextInt() int {
	n, err := strconv.Atoi(nextString())
	if err != nil {
		fmt.Printf("strconv.Atoi failed: %v\n", err)
	}
	return n
}

type ElementKey int
type Node struct {
	key    ElementKey
	parent *Node
	rank   int
}

func newNode(key ElementKey) *Node {
	node := Node{}
	node.key = key
	node.parent = &node
	node.rank = 0

	return &node
}

func union(x, y *Node) {
	xSet := findSet(x)
	ySet := findSet(y)
	link(xSet, ySet)
}

func link(x, y *Node) {
	if x.rank > y.rank {
		y.parent = x
	} else {
		x.parent = y

		if x.rank == y.rank {
			y.rank++
		}
	}
}

func findSet(x *Node) *Node {
	if x != x.parent {
		x.parent = findSet(x.parent)
	}
	return x.parent
}

func newDisjointSets(nSets int) *DisjointSets {
	sets := DisjointSets{}
	sets.keyToNode = map[ElementKey]*Node{}
	for i := 0; i < nSets; i++ {
		key := ElementKey(i)
		sets.keyToNode[key] = newNode(key)
	}
	return &sets
}

type DisjointSets struct {
	keyToNode map[ElementKey]*Node
}

func (sets *DisjointSets) union(x, y ElementKey) {
	xNode := sets.keyToNode[x]
	yNode := sets.keyToNode[y]
	union(xNode, yNode)
}

func (sets DisjointSets) findSet(x ElementKey) *Node {
	xNode := sets.keyToNode[x]
	return findSet(xNode)
}

type Edge struct {
	i, j   int
	weight int
}

func main() {
	scanner.Split(bufio.ScanWords)

	n := nextInt()
	sets := newDisjointSets(n)
	edges := []Edge{}
	a := make([][]int, n)
	for i := 0; i < n; i++ {
		a[i] = make([]int, n)
		for j := 0; j < n; j++ {
			a[i][j] = nextInt()
			if a[i][j] >= 0 {
				e := Edge{
					i:      i,
					j:      j,
					weight: a[i][j],
				}
				edges = append(edges, e)
			}
		}
	}
	sort.Slice(edges, func(i, j int) bool { return edges[i].weight < edges[j].weight })
	totalWeight := 0
	for _, edge := range edges {
		i := ElementKey(edge.i)
		j := ElementKey(edge.j)
		if sets.findSet(i) != sets.findSet(j) {
			totalWeight += edge.weight
			sets.union(i, j)
		}
	}
	fmt.Println(totalWeight)
}

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: #coding: utf-8

inf = 1000000000
n = int(input())
mtrx = []
for i in range(n):
    col2 = list(map(int,input().split()))
    col = []
    for num in col2:
        if num == -1:
            num = inf
        col.append(num)
    mtrx.append(col)

def prim():
    color = ["white" for i in range(n)]
    d = [inf for i in range(n)]
    p = [None for i in range(n)]
    p[0] = -1
    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))

prim()

Python: 
def prim():
    global n, color, M, d, p
    d[0] = 0

    while True:
        min_cost = 10000000000
        u = -1

        # まず始点を決める。
        for i in range(n):
            if color[i] != 'BLACK' and d[i] < min_cost:
                min_cost = d[i]
                u = i  # エッジが繋がる中で、最小のもの？？

        if u == -1:
            break

        color[u] = 'BLACK'

        for v in range(n):
            if color[v] != 'BLACK' and M[u][v] != -1:
                if d[v] > M[u][v]:
                    d[v] = M[u][v]
                    p[v] = u
                    color[v] = 'GRAY'

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

    return sum


n = int(input())

color = ['WHITE'] * n
M = []
d = [10000000000] * n  # 重みが最小の辺の重み
p = [-1] * n  # MSTにおけるp[v]の親（どこから来たか？？）

for i in range(n):
    _ = list(map(int, input().split()))
    M.append(_)
# print(A)

print(prim())

Python: #0オリジンで行うので注意
import sys
input = sys.stdin.buffer.readline

INF = 10 ** 9


#隣接行列
n = int(input())
G = []
for _ in range(n):
    G.append(list(map(int, input().split())))
for i in range(n):
    for j in range(n):
        if G[i][j] == -1:
            G[i][j] = INF

#到着してない：white,　到着後:gray, 確定:black
white, gray, black = 1, 2, 3
color = [white] * n #初期条件

d = [INF] * n #d[m]にTに属する頂点とT-Vに属する頂点を繋ぐ辺の中で重みが最小の物を記録
p = [INF] * n #p[m]にMSTにおける頂点mの親を記録


def prim():
    d[0] = 0
    p[0] = -1
    
    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
            break
                
        color[u] = black #最小全域木の頂点として決定
            
        for v in range(n):
            if color[v] != black and G[u][v] != INF:
                if G[u][v] < d[v]:
                    d[v] = G[u][v] #d[n]を更新を更新する
                    p[v] = u #uをvの親候補として記録
                    color[v] = gray
    
    S = 0#合計
    for i in range(n):
        if p[i] != -1:
            S += G[i][p[i]]
    return S

print(prim())

Python: MAX = 2001


def prim(tree: [int], adjacent_list: [[int]]):
    cost = 0
    next = 0
    for l in adjacent_list:
        l[next] = MAX
    while True:
        tree.append(next)
        min_list = list()
        for t in tree:
            min_list.append(min([(v, i) for i, v in enumerate(adjacent_list[t])]))
        min_cost, i = min(min_list)
        if min_cost == MAX:
            return cost
        cost += min_cost
        for l in adjacent_list:
            l[i] = MAX
        print(adjacent_list)
        next = i


if __name__ == '__main__':
    N = int(input())
    adjacent_list = [[int(e) if int(e) != -1 else MAX for e in input().rstrip().split()] for _ in range(N)]
    test_list = []
    print(prim(test_list, adjacent_list))
    print(test_list)

Python: import sys
import itertools
sys.setrecursionlimit(1000000000)
from heapq import heapify,heappop,heappush,heappushpop
import math
import collections
import copy
import decimal
INF = 10**18
WHITE = 0
GRAY = 1
BLACK = 2

def Prim():
    d = [INF]*(n)
    c = [WHITE]*(n)
    p = [-1]*(n)

    d[0] = 0
    while True:
        minv = INF
        u = -1
        for i in range(n):
            if minv > d[i] and c[i] != BLACK:
                u = i
                minv = d[i]
        if u == -1:
            break
        c[u] = BLACK
        for v in range(n):
            if c[v] != BLACK and G[u][v] != INF:
                if d[v] > G[u][v]:
                    d[v] = G[u][v]
                    p[v] = u
                    c[v] = GRAY
    sum_g = 0
    for i in range(n):
        if p[i] != -1:
            sum_g += G[i][p[i]]
    return sum_g


if __name__ == "__main__":
    n = int(input())
    G = []
    for i in range(n):
        s = list(map(int,input().split()))
        G.append(s)
    for i in range(n):
        for j in range(n):
            if G[i][j] == -1:
                G[i][j] = INF
    ans = Prim()
    print(ans)