Go: package main

import (
	"bufio"
	"container/heap"
	"fmt"
	"os"
	"strconv"
)

type Node struct {
	id     int
	weight int
}

func init() {
	sc.Split(bufio.ScanWords)
}

type NodeHeap []Node

func (h NodeHeap) Len() int           { return len(h) }
func (h NodeHeap) Less(i, j int) bool { return h[i].weight < h[j].weight }
func (h NodeHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }

func (h *NodeHeap) Push(x interface{}) {
	*h = append(*h, x.(Node))
}

func (h *NodeHeap) Pop() interface{} {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[0 : n-1]
	return x
}

var sc = bufio.NewScanner(os.Stdin)

func scanInt() int {
	num, _ := strconv.Atoi(scanString())
	return num
}

func scanString() string {
	sc.Scan()
	return sc.Text()
}

func init() {
	sc.Split(bufio.ScanWords)
}

func main() {
	n := scanInt()

	list := make([][]int, n)
	seen := make([]bool, n)
	for i := range list {
		list[i] = make([]int, n)
		for j := range list[i] {
			list[i][j] = scanInt()
		}
	}

	start := Node{id: 0, weight: 0}
	h := &NodeHeap{start}
	heap.Init(h)

	sum := 0
	for h.Len() > 0 {
		node := heap.Pop(h).(Node)
		if seen[node.id] {
			continue
		}
		seen[node.id] = true
		sum += node.weight

		for i, w := range list[node.id] {
			if w < 0 {
				continue
			}
			heap.Push(h, Node{id: i, weight: w})
		}
	}

	fmt.Println(sum)
}

Python: a=input()
matrix=[]
for i in range(int(a)):
	matrix.append(list(map(int,input().split())))

# ?????????O(n)????????£?????????
class union_find(object):
 	"""union-find tree"""
 	def __init__(self, length):
 		self.length = length
 		self.unionnumber=0
 		self.unionlist=[[]]
 		self.num=list(-1 for i in range(length))

 	def unite(self,i,j):
 		if self.num[i]==-1:
 			if self.num[j]==-1:
 				self.unionlist[self.unionnumber].extend([i,j])
 				self.num[i]=self.unionnumber
 				self.num[j]=self.unionnumber
 				self.unionnumber+=1
 				self.unionlist.append([])
 			else:
 				tmp=i 
 				i=j 
 				j=tmp 
 		if self.num[i]!=-1:
 			if self.num[j]!=-1:
 				if self.num[i]==self.num[j]:
 					pass
 				else:
 					self.unionlist[self.num[i]].extend(self.unionlist[self.num[j]])
 					tmp=self.num[j]
 					for k in self.unionlist[self.num[j]]:
 						self.num[k]=self.num[i]
 					self.unionlist[tmp]="del"
 			else:
 				self.num[j]=self.num[i]
 				self.unionlist[self.num[i]].append(j)

 	def same(self,i,j):
 		if self.num[i]==-1 or self.num[j]==-1:
 			return(False)
 		else:
 			return(self.num[i]==self.num[j])

# ?????????=-1
def Kruskal(matrix):
	length=len(matrix)
	edgelist=[]
	for i in range(length):
		for j in range(i+1):
			if matrix[i][j]!=-1:
				edgelist.append([j,i,matrix[i][j]])
	edgelist.sort(key=lambda x:x[2],reverse=True)
	result=[[-1 for i in range(length)] for j in range(length)]
	union=union_find(length)
	while(edgelist!=[]):
		edge=edgelist.pop()
		i,j,score=edge
		if union.same(i,j):
			pass
		else:
			union.unite(i,j)
			result[i][j]=score
			result[j][i]=score
		
	return(result)

a=Kruskal(matrix)
count=0
for i in range(len(a)):
	for j in range(i):
		if a[i][j]!=-1:
			count+=a[i][j]

print(count)

Python: INF = 1e9

n = int(input())
adj_matrix = [list(map(int, input().split())) for i in range(n)]


def prim(x):
    isVisited = [False] * x
    d = [INF] * x 
    d[0] = 0
    p = [-1] * x 
    
    while True:
        min_cost = INF
        
        for i in range(x):
            if isVisited[i] != True and d[i] < min_cost:
                min_cost = d[i]
                u = i
        
        if min_cost == INF:
            break
        
        isVisited[u] = True
        
        for v in range(x):
            if isVisited[v] != True and adj_matrix[u][v] != -1:
                if adj_matrix[u][v] < d[v]:
                    d[v] = adj_matrix[u][v]
                    p[v] = u
    return sum(d)

print(prim(n))

Python: n = int(input())
m = []

for _ in range(n):
    tmp = [int(x) for x in input().split()]
    m.append(tmp)

#辺を全て持つリストを作る
edge_list = [] 
j = 1
for i in range(n-1):
    for k,x in enumerate(m[i][j:]):
        if x != -1:
            edge_list.append((x,i,k+j))
        else:
            pass
    j += 1
edge_list.sort()

root_list = [i for i in range(n)]

def root(x):
    path_to_root = []
    while root_list[x] != x:
        path_to_root.append(x)
        x = root_list[x]
    for node in path_to_root:
        root_list[node] = x
    return x

def is_same_root(x,y):
    return root(x) == root(y)

def unite(x,y):
    root_list[root(x)] = root(y)

cost = 0
for x in edge_list:
    w,p,q = x
    if is_same_root(p,q):
        continue
    else:
        cost += w
        unite(p,q)

print(cost)

Python: inf = float("inf")
class Node():

    def __init__(self, _id):
        self.id = _id
        self.d = inf
        self.pi = None
        self.color = 0
    
    def input_data(self):
        data = [int(i) for i in input().split()]
        self.adj = {G[i]: d
                    for i, d in enumerate(data)
                    if d != -1}
    
    def __hash__(self):
        return hash(self.id)
        
    

def prim():
    G[0].d = 0
    while True:
        mincost = inf
        for i in G:
            if i.color != 1 and i.d < mincost:
                mincost = i.d
                u = i
        
        if mincost == inf:
            break

        u.color = 1
        for v in u.adj.keys():
            if v.color != 1 and u.adj[v] < v.d:
                v.pi = u.id
                v.d = u.adj[v]

if __name__ == "__main__":
    n = int(input())
    G = [Node(i) for i in range(n)]
    [i.input_data() for i in G]
    prim()
    print(sum(g.d for g in G))

Python: n = int(input())
inf = float('inf')
graphs = []

for i in range(n):
    weights = list(map(int, input().split()))
    weights = [inf if weight == -1 else weight for weight in weights]
    graphs.append(weights)
# print(graphs)
# M =graphs
color = ['WHITE' for _ in range(n)]
d = [inf for _ in range(n)]
p = [i for i in range(n)]


def prim():
    d[0] = 0
    p[0] = -1
    while True:
        min_cost = inf
        for i in range(n):
            if color[i] != 'BLACK' and d[i] < min_cost:
                min_cost = d[i]
                u = i
        if min_cost == inf:
            break
        color[u] = 'BLACK'

        for v in range(n):
            if color[v] != 'BLACK' and graphs[u][v] != inf:
                if graphs[u][v] < d[v]:
                    d[v] = graphs[u][v]
                    p[v] = u
                    color[v] = 'GRAY'


prim()
# print(d)
# print(p)
print(sum(d))

Python: def main():
    N = int(input())
    c = [[int(i) for i in input().split()] for j in range(N)]
    edges = []
    for i in range(N):
        for j in range(i+1, N):
            if c[i][j] != -1:
                edges.append((c[i][j], (i, j)))
    edges.sort()

    par = [i for i in range(N)]
    rank = [0 for i in range(N)]

    def find_root(x):
        if par[x] == x:
            return x
        else:
            par[x] = find_root(par[x])
            return par[x]

    def is_same_group(x, y):
        return find_root(x) == find_root(y)

    def unite(x, y):
        x = find_root(x)
        y = find_root(y)
        if x == y:
            return
        if rank[x] < rank[y]:
            par[x] = y
        else:
            par[y] = x
            if rank[x] == rank[y]:
                rank[x] += 1

    ans = 0
    for c, e in edges:
        if find_root(e[0]) != find_root(e[1]):
            unite(e[0], e[1])
            ans += c
    print(ans)


if __name__ == '__main__':
    main()