Go: package main

import (
	"fmt"
	"sort"
)

type Edge struct {
	I int
	J int
	A int
}

func main() {
	var n int
	fmt.Scan(&n)

	g := make([][]int, n)
	edges := make([]Edge, 0, n*(n-1)/2)
	parents := make([]int, n)
	for i := 0; i < n; i++ {
		g[i] = make([]int, n)
		for j := 0; j < n; j++ {
			fmt.Scan(&g[i][j])
			if g[i][j] > 0 {
				edges = append(edges, Edge{i, j, g[i][j]})
			}
		}
		parents[i] = i
	}
	sort.SliceStable(edges, func(i, j int) bool { return edges[i].A > edges[j].A })

	sum := 0
	for len(edges) > 0 {
		edge := edges[len(edges)-1]
		edges = edges[:len(edges)-1]

		if same(edge.I, edge.J, &parents) {
			continue
		}
		union(edge.I, edge.J, &parents)
		sum += edge.A
	}
	fmt.Println(sum)
}



func root(id int, parents *[]int) int {
	if id == (*parents)[id] {
		return id
	}
	return root((*parents)[id], parents)
}

func union(i, j int, parents *[]int) {
	(*parents)[root(j, parents)] = (*parents)[root(i, parents)]
}

func same(i, j int, parents *[]int) bool {
	return root(i, parents) == root(j, parents)
}

Python: # -*- coding: utf-8 -*-
def prim(edges, *, start=0, adj_matrix=False, default_value=float('inf')):
    '''
    Returns the Minimum Spanning Tree(MST) of a given graph

    # sample input when given as adjacency matrix
    edges = [[0, 2, 5, 4, inf, inf],           # node 0
             [2, 0, inf, 3, 6, inf],           # node 1
             [5, inf, 0, 2, inf, 6],           # node 2
             [4, 3, 2, 0, 2, inf],             # node 3
             [inf, 6, inf, 2, 0, 4],           # node 4
             [inf, inf, 6, inf, 4, 0]]         # node 5

    # sample input when given not as adjacency matrix
    edges = [[(1, 2), (2, 5), (3, 4)],         # node 0
             [(0, 2), (3, 3), (4, 6)],         # node 1
             [(0, 5), (3, 2), (5, 6)],         # node 2
             [(0, 4), (1, 3), (2, 2), (4, 2)], # node 3
             [(1, 6), (3, 2), (5, 4)],         # node 4
             [(2, 6), (4, 4)]]                 # node 5
    '''

    n = len(edges)
    mst = []
    cost = 0
    T = [start]

    while True:
        tmp_edges = [(cost, (u, v)) for u in T for v, cost in enumerate(edges[u]) if cost != default_value and v not in T] if adj_matrix else\
                    [(cost, (u, v)) for u in T for v, cost in edges[u] if v not in T]

        if tmp_edges:
            min_cost, min_edge = min(tmp_edges)
            mst.append(min_edge)
            cost += min_cost
            T.append(min_edge[1])

        else:
            if len(mst) != n - 1:
                raise NoSpanningError(
                    'There is no spanning tree in this graph (search started from node{})'.
                    format(start))

            else:
                return mst, cost


class NoSpanningError(Exception):
    pass


if __name__ == '__main__':
    '''
    an example of using this function
    AIZU ONLINE JUDGE - ALDS_1_12_A
    '''

    n = int(input())
    edges = [[int(cost) if int(cost) != -1 else float('inf') for cost in input().split()] for i in range(n)]

    print(prim(edges, adj_matrix=True)[1])

Python: import heapq

def root(x):
    path_to_root = []
    while P[x] != x:
        path_to_root.append(x)
        x = P[x]
    for node in path_to_root:
        P[node] = x
    return x
def is_same_set(x,y):
    return root(x) == root(y)
def unite(x,y):
    P[root(x)] = root(y)

W = 0
N = int(input().strip())
P = [i for i in range(N)]
A = []
for i in range(N):
    v = list(map(int,input().strip().split(' ')))
    A.append(v)
edges = [] 
for i in range(N):
    for j in range(i,N):
        edge = [A[i][j],i,j]
        heapq.heappush(edges,edge)
while len(edges) > 0:
    e = heapq.heappop(edges)
    I = e[1]
    J = e[2]
    if e[0] != -1:
        if not is_same_set(I,J):
            unite(I,J)
            W += e[0]
print(W)

Python: # -*- coding: utf-8 -*-
from itertools import product

N = int(input())
INF = float("inf")
adj = []

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

not_MST = list(range(1, N))
MST = [0]

cost = 0
while len(not_MST):
    tmp_min = INF
    tmp_idx = -1
    for m, n in product(MST, not_MST):
        if adj[m][n] < tmp_min:
            tmp_min = adj[m][n]
            tmp_idx = n
    MST.append(tmp_idx)
    not_MST.remove(tmp_idx)
    cost += tmp_min

print(cost)

Python: import heapq


class MST:
    """Given weighted graph, find minimum spanning tree.

    >>> mst = MST([[-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]]);
    >>> mst.weight()
    5
    """
    MAX_WEIGHT = 2001

    def __init__(self, graph):
        self.graph = graph
        self.size = len(graph)
        self.tree = []
        self._search()

    def weight(self):
        return sum([self.graph[i][j] for i, j in self.tree])

    def _search(self):
        visited = [0]

        while len(visited) < self.size:
            h = []
            for node in visited:
                for i, w in enumerate(self.graph[node]):
                    if w == -1:
                        continue
                    if i in visited:
                        continue
                    heapq.heappush(h, (w, node, i))

            weight, src, dst = heapq.heappop(h)
            visited.append(dst)
            self.tree.append((src, dst))


def run():
    n = int(input())

    nodes = []
    for _ in range(n):
        nodes.append([int(i) for i in input().split()])

    mst = MST(nodes)
    print(mst.weight())


if __name__ == '__main__':
    run()

Python: N=int(input())
graph=[]
d=[2000]*(N)
p=[None]*(N)
color=["white"]*(N+1)
for i in range(N):
    a=list(map(int,input().split()))
    graph.append(a)
def prim():
    d[0]=0
    p[0]=-1
    while (True):
        mincost=2000
        for i in range(N):
            if color[i]!="black" and d[i]<mincost:
                mincost=d[i]
                u=i
        if mincost==2000:break
        color[u]="black"
        for v in range(N):
            if color[v]!="black" and graph[u][v]!=-1:
                if graph[u][v]<d[v]:
                    d[v]=graph[u][v]
                    p[v]=u
                    color[v]="gray"
prim()
print(sum(d))

Python: import sys

def readinput():
    n=int(input())
    nMat=[]
    for _ in range(n):
        m=list(map(int,input().split()))
        nMat.append(m)
    
    return n,nMat

WHITE=0
GRAY=1
BLACK=2
INFTY=sys.maxsize
def prim(n,nMat):

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

    d[0]=0
    p[0]=-1

    while True:
        mincost=INFTY
        for i in range(n):
            if color[i]!=BLACK and d[i] < mincost:
                mincost=d[i]
                u=i

        if mincost==INFTY:
            break

        # Tに属する頂点とV-Tに属する頂点をつなぐ辺の中で最小のコストのもの(u,p[u])が選ばれた
        color[u]=BLACK

        # V-Tに属する各頂点vとTに属する頂点をつなぐ辺の中で最小のコストのものが(v,p[v])でそのコストがd[v]
        # uがTに入ったことで辺(u,v)のコストとd[v]を比べてd[v]が大きかったらp[v]=u, d[v]=辺(u,v)のコストで更新
        for v in range(n):
            if color[v]!=BLACK and nMat[u][v]!=-1:
                if nMat[u][v]<d[v]:
                    d[v]=nMat[u][v]
                    p[v]=u
                    color[v]=GRAY
    return p,d


def main(n,nMat):
    p,d=prim(n,nMat)
    
    ans=0
    for i in range(n):
        if p[i] != -1:
            ans+=d[i]
    
    return ans

if __name__=='__main__':
    n,nMat=readinput()
    ans=main(n,nMat)
    print(ans)