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

Python: import sys

if __name__ == "__main__":
    # lines = """5
    # -1 2 3 1 -1
    # 2 -1 -1 4 -1
    # 3 -1 -1 1 1
    # 1 4 1 -1 3
    # -1 -1 1 3 -1
    # """.split("\n")
    lines = sys.stdin.readlines()
    matrix = [[int(x) for x in line.strip().split(" ")] for line in lines[1:] if line.strip() != ""]

    connections = set([0])  # ??\?¶????????????????
    dimension = int(lines[0])
    cost = 0

    while len(connections) < dimension:
        minimum = sys.maxsize
        candidate = None

        for i in connections:
            for index, value in enumerate(matrix[i]):
                if value != -1 and value < minimum and index not in connections:
                    minimum = matrix[i][index]  # minimum = value
                    candidate = index

        connections.add(candidate)
        cost += minimum

    # print(connections, cost)
    print(cost)

Python: from heapq import heappush, heappop, heapify

n = int(input())
G = [[] for _ in range(n)]

for i in range(n):
    for j,dist in enumerate(map(int,input().split())):
        if dist != -1:
            G[i].append((j,dist))
sum = 0

def prim(n):
    que = [(w,c) for c,w in G[0]]
    heapify(que)
    color = [0]*n
    color[0] = 1
    global sum
    while que:
        w,node = heappop(que)
        if color[node] == 1:
            continue
        color[node] = 1
        sum += w
        for x,y in G[node]:
            if color[x] == 1:
                continue
            heappush(que,(y,x))
    return sum

print(prim(n))

Python: from enum import Enum


class Mst(object):
    """ minimum spanning tree """
    INFINITY = 999999999
    class Status(Enum):
        """ ?????????????¨??????¶??? """
        white = 1  # ????¨????
        gray = 2  # ?¨???????
        black = 3  #?¨???????

    def __init__(self, data):
        num_of_nodes = len(data)+1
        self.color = [Mst.Status.white] * (num_of_nodes + 1)  # ????????????????¨??????¶???
        self.M = self._make_matrix(data)  # data????????????????????£??\??????
        self.d = [Mst.INFINITY] * num_of_nodes
        self.p = [-1] * num_of_nodes

    def _make_matrix(self, data):
        graph_table = []
        for d in data:
            t = [self.inf_or_num(x) for x in d]
            graph_table.append(t)
        return graph_table

    def inf_or_num(self, n):
        if n == -1:
            return Mst.INFINITY
        else:
            return n

    def prim(self):
        self.d[0] = 0
        self.p[0] = -1

        while True:
            mincost = Mst.INFINITY
            for i in range(len(self.d)-1):
                if self.color[i] != Mst.Status.black and self.d[i] < mincost:
                    mincost = self.d[i]
                    u = i

            if mincost == Mst.INFINITY:
                break

            self.color[u] = Mst.Status.black
            for v in range(len(self.d)-1):
                if self.color[v] != Mst.Status.black and self.M[u][v] != Mst.INFINITY:
                    if self.M[u][v] < self.d[v]:
                        self.d[v] = self.M[u][v]
                        self.p[v] = u
                        self.color[v] = Mst.Status.gray

        results = []
        for i in range(len(self.p)):
            if self.p[i] != -1:
                results.append(self.M[i][self.p[i]])
        return sum(results)



if __name__ == '__main__':
    # ??????????????\???
    n = int(input())
    data = []
    for _ in range(n):
        data.append(list(map(int, input().strip().split(' '))))

    mst = Mst(data)
    print(mst.prim())

Python: n = int(input())
primINF = 2000000000
matrix = []
numV = n
for i in range(n):
    matrix.append(list(map(int, input().split())))

visited = [False] * numV
cost = [primINF] * numV # cost
parent = [-1] * numV # parent node

cost[0] = 0
parent[0] = -1

while True:
    # 訪問済み隣接の最小コストのノードを探索する
    mincost = primINF
    for i in range(n):
        if visited[i] is False and cost[i] < mincost:
            mincost = cost[i]
            u = i
    # 見つからなければ終了する
    if mincost == primINF:
        break
    # 訪問済みにする
    visited[u] = True
    for v in range(n):
        if visited[v] is False and matrix[u][v] != -1:
            if matrix[u][v] < cost[v]:
                cost[v] = matrix[u][v]
                parent[v] = u
res = 0
for i in range(n):
    if parent[i] != -1:
        res += matrix[i][parent[i]]

print(res)