Go: package main

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

const (
	MAX   = 100
	INFTY = 1 << 21
	NIL   = -1
)

const (
	WHITE = iota
	GRAY
	BLACK
)

type Graph [MAX][MAX]int

func (g *Graph) prim(n int) int {
	var (
		u, minv     = 0, 0
		d, p, color [MAX]int
	)

	for i := 0; i < n; i++ {
		d[i] = INFTY
		p[i] = -1
		color[i] = WHITE
	}
	d[0] = 0

	for {
		minv = INFTY
		u = -1
		for i := 0; i < n; i++ {
			if minv > d[i] && color[i] != BLACK {
				u = i
				minv = d[i]
			}
		}

		if u == -1 {
			break
		}

		color[u] = BLACK
		for v := 0; v < n; v++ {
			if color[v] != BLACK && g[u][v] != INFTY {
				if d[v] > g[u][v] {
					d[v] = g[u][v]
					p[v] = u
					color[v] = GRAY
				}
			}
		}
	}

	sum := 0
	for i := 0; i < n; i++ {
		if p[i] != -1 {
			sum += g[i][p[i]]
		}
	}

	return sum
}

func answer(reader io.Reader) string {
	sc := bufio.NewScanner(reader)
	sc.Split(bufio.ScanWords)

	sc.Scan()
	n, _ := strconv.Atoi(sc.Text())

	var g Graph
	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			sc.Scan()
			e, _ := strconv.Atoi(sc.Text())
			if e == -1 {
				g[i][j] = INFTY
				continue
			}
			g[i][j] = e
		}
	}

	return fmt.Sprint(g.prim(n))
}

func main() {
	fmt.Println(answer(os.Stdin))
}

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)

Python: from heapq import heappush, heappop, heapify
from typing import List, Tuple


if __name__ == "__main__":
    num_vertices = int(input())
    adj_list: List[List[Tuple[int, int]]] = [[] for _ in range(num_vertices)]

    for vertex in range(num_vertices):
        for adj, cost in enumerate(map(lambda x: int(x), input().split())):
            if -1 != cost:
                # Store values as (cost, adj) to aplly heapify to cost values.
                adj_list[vertex].append((cost, adj))

    visited: List[bool] = [False] * num_vertices
    # Set the root node.
    que = [(cost, adj) for cost, adj in adj_list[0]]
    visited[0] = True
    heapify(que)

    total_cost = 0
    while [] != que:
        cost, adj = heappop(que)
        if visited[adj]:
            continue
        visited[adj] = True
        total_cost += cost
        for n_cost, n_adj in adj_list[adj]:
            if visited[n_adj]:
                continue
            heappush(que, (n_cost, n_adj))

    print(total_cost)

Python: import heapq

n = int(input())
A = [[int(i) for i in input().split()] for i in range(n)]
h = []
DP = {}
heapq.heappush(h,(0,0))
c = 0
while(len(DP)<n):
    tmp = heapq.heappop(h)
    if tmp[1] in DP:
        continue
    c += tmp[0]
    DP[tmp[1]] = 1
    for i,j in enumerate(A[tmp[1]]):
        if j > -1 and not i in DP:
            heapq.heappush(h,(j,i))
print(c)

Python: n=int(input())
inf=10000
color=["white" for i in range(n)]
p=[-1 for i in range(n)]
d=[inf for i in range(n)]
M=[[] for i in range(n)]


for i in range(n):
    tmp=list(map(int,input().split()))
    for j in range(n):
        if tmp[j]==-1:
            M[i].append(inf)
        else:
            M[i].append(tmp[j])

def prim():
    d[0]=0
    while True:
        mincost=inf
        for i in range(n):
            if mincost>d[i] and color[i]!="black":
                mincost=d[i]
                u=i
        if mincost==inf:
            break
        color[u]="black"
        for j in range(n):
            if color[j]!="black" and M[u][j]!=inf:
                if M[u][j]<d[j]:
                    d[j]=M[u][j]
                    p[j]=u
                    color[j]="gray"

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.pop(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)]
for v in range(N):
    for w, c in enumerate(map(int, input().split())):
        if c != -1:
            G[v].append((w, c))

from heapq import heappush, heappop, heapify
used = [0]*N
que = [(c, w) for w, c in G[0]]
used[0] = 1
heapify(que)

ans = 0
while que:
    cv, v = heappop(que)
    if used[v]:
        continue
    used[v] = 1
    ans += cv
    for w, c in G[v]:
        if used[w]:
            continue
        heappush(que, (c, w))
print(ans)