Go: package main

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

var scanner = bufio.NewScanner(os.Stdin)

func nextString() string {
	scanner.Scan()
	return scanner.Text()
}

func nextInt() int {
	n, err := strconv.Atoi(nextString())
	if err != nil {
		fmt.Printf("strconv.Atoi failed: %v\n", err)
	}
	return n
}

type ElementKey int
type Node struct {
	key    ElementKey
	parent *Node
	rank   int
}

func newNode(key ElementKey) *Node {
	node := Node{}
	node.key = key
	node.parent = &node
	node.rank = 0

	return &node
}

func union(x, y *Node) {
	xSet := findSet(x)
	ySet := findSet(y)
	link(xSet, ySet)
}

func link(x, y *Node) {
	if x.rank > y.rank {
		y.parent = x
	} else {
		x.parent = y

		if x.rank == y.rank {
			y.rank++
		}
	}
}

func findSet(x *Node) *Node {
	if x != x.parent {
		x.parent = findSet(x.parent)
	}
	return x.parent
}

func newDisjointSets(nSets int) *DisjointSets {
	sets := DisjointSets{}
	sets.keyToNode = map[ElementKey]*Node{}
	for i := 0; i < nSets; i++ {
		key := ElementKey(i)
		sets.keyToNode[key] = newNode(key)
	}
	return &sets
}

type DisjointSets struct {
	keyToNode map[ElementKey]*Node
}

func (sets *DisjointSets) union(x, y ElementKey) {
	xNode := sets.keyToNode[x]
	yNode := sets.keyToNode[y]
	union(xNode, yNode)
}

func (sets DisjointSets) findSet(x ElementKey) *Node {
	xNode := sets.keyToNode[x]
	return findSet(xNode)
}

type Edge struct {
	i, j   int
	weight int
}

func main() {
	scanner.Split(bufio.ScanWords)

	n := nextInt()
	sets := newDisjointSets(n)
	edges := []Edge{}
	a := make([][]int, n)
	for i := 0; i < n; i++ {
		a[i] = make([]int, n)
		for j := 0; j < n; j++ {
			a[i][j] = nextInt()
			if a[i][j] >= 0 {
				e := Edge{
					i:      i,
					j:      j,
					weight: a[i][j],
				}
				edges = append(edges, e)
			}
		}
	}
	sort.Slice(edges, func(i, j int) bool { return edges[i].weight < edges[j].weight })
	totalWeight := 0
	for _, edge := range edges {
		i := ElementKey(edge.i)
		j := ElementKey(edge.j)
		if sets.findSet(i) != sets.findSet(j) {
			totalWeight += edge.weight
			sets.union(i, j)
		}
	}
	fmt.Println(totalWeight)
}

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