Go: package main

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

//util
var sc = bufio.NewScanner(os.Stdin)

func nextStr() string {
	sc.Scan()
	return sc.Text()
}

func nextInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}

func printList(list []int) {
	n := len(list)
	buf := bufio.NewWriter(os.Stdout)
	for _, v := range list[0 : n-1] {
		buf.Write([]byte(fmt.Sprintf("%d ", v)))
	}
	buf.Write([]byte(fmt.Sprintf("%d\n", list[n-1])))
	buf.Flush()
}

func max(a, b int) int {
	if a > b {
		return a
	} else {
		return b
	}
}

func min(a, b int) int {
	if a > b {
		return b
	} else {
		return a
	}
}

//solve
const (
	MAX   = 100
	INFTY = (1 << 21)
	WHITE = 0
	GRAY  = 1
	BLACK = 2
)

//V: グラフの頂点全体の集合
//T: MSTに属する頂点の集合
var (
	n     int
	M     [MAX][MAX]int //重みを記録する隣接行列
	color [MAX]int
	p     [MAX]int //MSTにおける頂点の親を記録
	d     [MAX]int //Tに属する頂点と、V−Tに属する頂点を繋ぐ辺の中で、重みが最小のものを記録
)

func prim() int {
	var u, minv int
	//初期化
	for i := 0; i < n; i++ {
		d[i] = INFTY
		p[i] = -1
		color[i] = WHITE
	}

	d[0] = 0

	for {
		//頂点uを決めていく
		//つまり、Tに属する頂点と、V−Tに属する頂点を繋ぐ辺の中で、重みが最小のものを決める
		minv = INFTY
		u = -1
		for i := 0; i < n; i++ {
			//未訪問かつ、辺の重みが最小となるuを選ぶ
			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 && M[u][v] != INFTY {
				if d[v] > M[u][v] {
					d[v] = M[u][v]
					p[v] = u
					color[v] = GRAY
				}
			}
		}
	}

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

func main() {
	sc.Split(bufio.ScanWords)
	n = nextInt()

	for i := 0; i < n; i++ {

		for j := 0; j < n; j++ {
			tmp := nextInt()
			if tmp == -1 {
				tmp = INFTY
			}
			M[i][j] = tmp
		}

	}

	fmt.Println(prim())

}

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())