Go: package main

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

const (
	WHITE int = iota
	GRAY
	BLACK
)

type graph struct {
	G [][]int
	C []int
	D []int
	P []int
}

var INFTY = 1 << 32

func constructGraph() *graph {
	sc := bufio.NewScanner(os.Stdin)
	sc.Scan()
	n, _ := strconv.Atoi(sc.Text())

	g := make([][]int, n)
	c := make([]int, n)
	d := make([]int, n)
	p := make([]int, n)

	for i := 0; i < n; i++ {
		sc.Scan()
		fields := strings.Fields(sc.Text())
		g[i] = toIntSlice(fields)
	}

	return &graph{g, c, d, p}
}

func (g *graph) initMst() {
	for i := 0; i < len(g.G); i++ {
		g.C[i] = WHITE
		g.D[i] = INFTY
	}
	g.D[0] = 0
	g.P[0] = -1
}

func (g *graph) primMst() int {
	g.initMst()

	var u int
	for {
		mincost := INFTY
		for i := 0; i < len(g.G); i++ {
			if g.C[i] != BLACK && g.D[i] < mincost {
				mincost = g.D[i]
				u = i
			}
		}

		if mincost == INFTY {
			break
		}

		g.C[u] = BLACK

		for i := 0; i < len(g.G); i++ {
			if g.C[i] != BLACK && g.existEdge(u, i) {
				if g.G[u][i] < g.D[i] {
					g.D[i] = g.G[u][i]
					g.P[i] = u
				}
			}
		}
	}

	totalCost := 0
	for _, cost := range g.D {
		totalCost += cost
	}
	return totalCost
}

func (g *graph) existEdge(u, v int) bool {
	return g.G[u][v] != INFTY && g.G[v][u] != INFTY
}

func toIntSlice(s []string) []int {
	a := make([]int, len(s))
	for i, v := range s {
		num, _ := strconv.Atoi(v)
		if num == -1 {
			num = INFTY
		}
		a[i] = num
	}
	return a
}

func main() {
	g := constructGraph()
	fmt.Println(g.primMst())
}

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)