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

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)