Go: package main

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

const R = 100000000

var sc = bufio.NewScanner(os.Stdin)

var n int
var A [101][101]int

func nextInt() int {
	sc.Scan()
	i, _ := strconv.Atoi(sc.Text())
	return i
}
func prim() int {
	var u, Minimum, sum int
	var d, p, color [101]int

	for i := 0; i < n; i++ {
		d[i] = R
		p[i] = -1
		color[i] = 0
	}
	d[0] = 0

	for {
		Minimum = R
		u = -1
		for i := 0; i < n; i++ {
			if Minimum > d[i] && color[i] != 2 {
				u = i
				Minimum = d[i]
			}
		}
		if u == -1 {
			break
		}
		color[u] = 2
		for j := 0; j < n; j++ {
			if color[j] != 2 && A[u][j] != R {
				if d[j] > A[u][j] {
					d[j] = A[u][j]
					p[j] = u
					color[j] = 1
				}
			}
		}
	}

	for i := 0; i < n; i++ {
		if p[i] != -1 {
			sum += A[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++ {
			e := nextInt()
			if e == -1 {
				A[i][j] = R
			} else {
				A[i][j] = e
			}
		}
	}
	fmt.Println(prim())
}

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)

Python: from heapq import heappush, heappop, heapify

N = int(input())
edges = [[] for i in range(N)]
for v in range(N):
    for w, c in enumerate(map(int, input().split())):
        if c != -1:
            edges[v].append((w, c))

visited = [0]*N
que = [(c, w) for w, c in edges[0]]
visited[0] = 1
heapify(que)

d=[0]+[10**9]*(N-1)

#左がコスト
ans = 0
while que:
    c, u = heappop(que)
    if visited[u]:
        continue
    visited[u] = 1
    d[u]=c
    for v, c in edges[u]:
        if visited[v]:
          continue
        heappush(que, (c, v))
print(sum(d))

Python: graph_n=int(input())


edge_dict={}



for i in range(graph_n):
    tmp_row=list(map(int,input()))
    for j in range(graph_n):
        if(tmp_row[j]!=-1):
            try:
                edge_dict[tmp_row].append([i,j])
            except:
                edge_dict[tmp_row]=[[i,j]]

sorted_edge=sorted(edge_dict.items())
vertex_flag=[0]*graph_n

searched_vertex_num=0
cost=0

for edges in sorted_edge:
    for edge in edges[1]:
        if(vertex_flag[edge[0]]==0 and vertex_flag[edge[1]]==0):
            vertex_flag[edge[0]]=1
            vertex_flag[edge[1]]=1
            seached_vertex_num+=2
            cost+=edges[0]
            if(graph_n <=searched_vertex_num):
                break

        elif(vertex_flag[edge[0]]==0 and vertex_flag[edge[1]]==1):
            vertex_flag[edge[0]]=1
            vertex_flag[edge[1]]=1
            seached_vertex_num+=1
            cost+=edges[0]
            if(graph_n <=searched_vertex_num):
                break

        elif(vertex_flag[edge[0]]==1 and vertex_flag[edge[1]]==0):
            vertex_flag[edge[0]]=1
            vertex_flag[edge[1]]=1
            seached_vertex_num+=1
            cost+=edges[0]
            if(graph_n <=searched_vertex_num):
                break

    if(graph_n <=searched_vertex_num):
        break


print(cost)

Python: # -*- coding: utf-8 -*-
'''
所要時間は、分位であった。
'''
# ライブラリのインポート
#import re #正規表現
import sys
#import heapq
import bisect
#import collections
#import math

def main():
    n = int(input())
    X = [[] for i in range(n)]
    l = []
    for i, line in enumerate(sys.stdin):
        X[i] = list(line.strip("\n").split())
        for j in range(i,n):
            c = int(X[i][j])
            if c == -1:
                continue
            else:
                r = (c,i,j)
                bisect.insort(l, r)
    
    uf = UnionFind(n)
    k = 0
    ans = 0
    count = 0
    while(count < n):
        try: tmp = l[k]
        except: break
        x = tmp[1]
        y = tmp[2]
        if not uf.same(x,y):
            uf.unite(x, y)
            ans += tmp[0] 
            count += 0
        k += 1
    print(ans)

class UnionFind:
    def __init__(self,n):
        self.p = [i for i in range(n)]
        return
    
    def root(self,x):
        while(1):
            if (self.p[x] == x): break
            y = x
            x = self.p[x]
            self.p[y] = self.p[x]
        return x

    def unite(self ,x, y):
        rx = self.root(x)
        ry = self.root(y)
        if rx == ry: return
        else:
            self.p[rx] = ry
            return 
    
    def same(self, x, y):
        rx = self.root(x)
        ry = self.root(y)
        return rx == ry


    
if __name__ == '__main__':
    main()