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: # -*- 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)