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: 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.heappop(queue)
    weight, one = q[0], q[1]
    if one in visited:
        continue
    answer += weight
    for e in edges[one]:
        if e[1] not in visited:
            heapq.heappush(queue, e)
    visited |= {one}
print(answer)

Python: import sys
INF = float('inf')
n = int(input())
adja_matrix = [[int(i) for i in line.split()] for line in sys.stdin.read().splitlines()]
condition = ['INIT'] * n
distance = [INF] * n
p = [0] * n
distance[0] = 0
p[0] = -1

while True:
    mincost = INF
    for i in range(n):
        if condition[i] != 'FINISH' and distance[i] < mincost:
            mincost = distance[i]
            u = i

    if mincost == INF:
        break

    condition[u] = 'FINISH'

    for v in range(n):
        if condition[i] != 'FINISH' and adja_matrix[u][v] != -1:
            if adja_matrix[u][v] < distance[v]:
                distance[v] = adja_matrix[u][v]
                p[v] = u
                condition[v] = 'CHECK'

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

print(sum)

Python: import heapq


def prim(G):
    n = len(G)
    is_visited = [False for _ in range(n)]
    que = []
    heapq.heappush(que, (0, 0))

    ret = 0
    while que:
        cost, cur_v = heapq.heappop(que)
        if is_visited[cur_v]:
            continue

        is_visited[cur_v] = True
        ret += cost
        for (adj_dst, adj_cost) in G[cur_v]:
            heapq.heappush(que, (adj_cost, adj_dst))

    return ret


def main():
    n = int(input())
    g = [[] for _ in range(n)]
    a = [[int(x) for x in input().split()] for _ in range(n)]

    for i in range(n):
        for j in range(n):
            if a[i][j] == -1:
                continue
            g[i].append((j, a[i][j]))
            g[j].append((i, a[i][j]))

    print(prim(g))


main()

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

WHITE = 0
GREY = 1
BLACK = 2
INFTY = 10**10

color = [WHITE] * n
d = [INFTY] * n
p = [-1] * n


def prim():
    # すべての頂点u について color[u] をwhiteとして、d[u]をINFINITYへ
    d[0] = 0
    p[0] = -1  # 親なし

    while True:
        mincost = INFTY
        for i in range(0, n):
            if color[i] != BLACK and d[i] < mincost:
                # まだ未訪問でコストが最小になるところを探す。
                # WHITEなところはd[i]=INFTYなので来ない
                mincost = d[i]
                # 最小コストになる場所を見つける
                u = i
                # 訪れる場所を決定
        if mincost == INFTY:
            break

        color[u] = BLACK
        # 起点座標の決定

        for v in range(0, n):
            if color[v] != BLACK and M[u][v] != -1:
                if M[u][v] < d[v]:
                    # 最初コストになるノードを探索
                    d[v] = M[u][v]
                    p[v] = u
                    color[v] = GREY


prim()
print(sum(d))

Python: INF = 99999999999999999999999999
n = int(input())
graph = [[-1] * (n+1) for _ in range(n+1)]
mst = [[-1] * (n+1) for _ in range(n+1)]
V = [ele for ele in range(1, n+1)]
T = []

for i in range(1, n + 1):
    tmp = [int(ele) for ele in input().split()]
    graph[i][1:] = tmp


def my_mst_solver():
    # あるノード n の辺の集合から、もっとも軽いもののindexを知りたい
    # sortされていればすぐだが、graphは添字と依存しているため、sortはできない
    # なので、(w,to) という形で表現された辺のリストがあると非常に便利になるのではないか。
    # これって隣接リストの拡張か？？まあいいや
    ans = 0
    edges = [[0]]
    for i in range(1, n + 1):
        tmp = []
        for to, w in enumerate(graph[i][1:], 1):
            if w != -1:
                tmp.append([w, to])
        tmp.sort()  # pythonのlist.sort()は安定ソートかつ、要素が配列の場合はele[0]でソートする
        edges.append(tmp)

    # 1. Gから任意の頂点 r を選び、それをMSTのルートとしてTに追加する
    root = 1
    T.append(root)
    # 2. 次の処理を T = V になるまで繰り返します。
    # Tに属する頂点と　V - T に属する頂点をつなぐ辺の中で、重みが最小のものである辺 (p_u, u) を選び、
    # それを MST の辺とし、 u を T に追加します

    while set(T) != set(V):
        tmp = [INF, INF]
        for i in T:
            if edges[i] != [] and edges[i][0] < tmp:
                tmp = edges[i][0]
                idx = i
        else:
            # T, MSTの更新
            ans += tmp[0]
            T.append(tmp[1])
            mst[idx][tmp[1]] = tmp[0]
            mst[tmp[1]][idx] = tmp[0]
            # edgesの更新
            for k in range(1, n + 1):
                edges[k] = list(filter(lambda x: x[1] not in T, edges[k]))

    print(ans)


if __name__ == "__main__":
    my_mst_solver()

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

    while True:
        mincost = float("inf")
        for i in range(n):
            if visited[i] != 2 and d[i] < mincost:
                mincost = d[i]
                u = i

        if mincost == float("inf"):
            break

        visited[u] = 2

        for v in range(n):
            if visited[v] != 2 and M[u][v] != float("inf"):
                if d[v] > M[u][v]:
                    d[v] = M[u][v]
                    p[v] = u
                    visited[v] = 1
                
    ans = 0
    for i,j in enumerate(p[1:], start=1):
        ans += M[i][j]
        
    return ans


n = int(input())
M = []

for _ in range(n):
    M.append([x if x != -1 else float("inf") for x in map(int, input().split())])


print(prim())