Go: package main

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

// Define disjoint-set forests

type vertexNo int

type vertex struct {
	number vertexNo
	rank int
	parent *vertex
}

func makeSet(number vertexNo) vertex {
	return vertex {
		number: number,
		rank: 0,
		parent: nil,
	}
}

func union(x, y *vertex) *vertex {
	return link(findSet(x), findSet(y))
}

func link(x, y *vertex) *vertex {
	if x.rank > y.rank {
		y.parent = x
		return x
	} else {
		x.parent = y
		if x.rank == y.rank {
			y.rank += 1
		}
		return y
	}
}

func findSet(v *vertex) *vertex {
	if v.parent == nil {
		return v
	}
	v.parent = findSet(v.parent)
	return v.parent
}

// Function to calculate minimum spanning tree

type matrix [][]int

type edge struct {
	one vertexNo
	two vertexNo
	weight int
}

const(
	MAX_VERTICES = 100
)

func newEdgesFromMatrix(matrix matrix) []edge {
	edges := make([]edge, 0, MAX_VERTICES * MAX_VERTICES)

	for i := 0; i < len(matrix); i++ {
		row := matrix[i]
		for j := i; j < len(row); j++ {
			if row[j] >= 0 {
				edge := edge{one: vertexNo(i+1), two: vertexNo(j+1), weight: row[j]}
				edges = append(edges, edge)
			}
		}
	}

	return edges
}

func solve(matrix matrix) int {
	nVertices := len(matrix)

	// initialize vertices
	vertices := make([]vertex, nVertices)
	for i := 0; i < nVertices; i++ {
		vertices[i] = makeSet(vertexNo(i+1))
	}

	// prepare edges sorted in the ascending order of weight
	edges := newEdgesFromMatrix(matrix)
	sort.Slice(edges, func(i, j int) bool {
		return edges[i].weight < edges[j].weight
	})

	unionCount := 0
	weightSum := 0
	for unionCount < nVertices-1 {
		for i := 0; i < len(edges); i++ {
			edge := edges[i]
			v1 := &vertices[edge.one-1]
			v2 := &vertices[edge.two-1]
			rep1 := findSet(v1)
			rep2 := findSet(v2)
			if rep1.number == rep2.number {
				continue
			}
			union(rep1, rep2)
			edges = append(edges[0:i], edges[i+1:]...)
			weightSum += edge.weight
			unionCount++
			break
		}
	}

	return weightSum
}

// main

func main() {
	sc := bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)

	n, err := nextInt(sc)
	if err != nil {
		panic(err)
	}

	matrix := parseMatrix(n, sc)

	edges := newEdgesFromMatrix(matrix)
	sort.Slice(edges, func(i, j int) bool {
		return edges[i].weight < edges[j].weight
	})

	fmt.Println(solve(matrix))
}

func parseMatrix(n int, sc *bufio.Scanner) [][]int {
	matrix := make([][]int, n)
	for i := 0; i < n; i++ {
		matrix[i] = make([]int, n)
		for j := 0; j < n; j++ {
			x, err := nextInt(sc)
			if err != nil {
				panic(err)
			}
			matrix[i][j] = x
		}
	}
	return matrix
}

func nextText(sc *bufio.Scanner) string {
	sc.Scan()
	return sc.Text()
}

func nextInt(sc *bufio.Scanner) (int, error) {
	return strconv.Atoi(nextText(sc))
}

Python: v = int(input())
G= [[int(i) for i in input().split()] for i in range(v)]
        
def prim(G, v):
    Vn = set([1])
    En = set([])
    V = set(range(1, v+1))
    while Vn != V:
        m = float('inf')
        for u in Vn:
            for v in V - Vn:
                if G[u - 1][v - 1] == -1:continue
                if G[u - 1][v - 1] < m:
                    m = G[u - 1][v -1]
                    k = (u,v)
        Vn.add(k[1])
        En.add(k)
    return En

print(sum(G[u - 1][v -1] for u,v in prim(G, v)))

Python: import sys

def debug(x, table):
    for name, val in table.items():
        if x is val:
            print('DEBUG:{} -> {}'.format(name, val), file=sys.stderr)
            return None

def solve():
    n = int(input())
    a = []

    for i in range(n):
        a.append([int(j) for j in input().split()])

    checked = [False] * n
    tree = [0]
    checked[0] = True
    ans = 0

    for i in range(n - 1):
        min_w = float('inf')

        for u in tree:
            for j in range(n):
                if a[u][j] != -1 and not checked[j]:
                    if min_w > a[u][j]:
                        min_w = a[u][j]
                        min_n = j

        checked[min_n] = True
        tree.append(min_n)
        ans += min_w

    print(ans)



if __name__ == '__main__':
    solve()

Python: # Minimum Spanning Tree

INF = 10**5
N, *W = map(int, open(0).read().split())
W = tuple(zip(*[iter(INF if w < 0 else w for w in W)]*N))

S = set([0])
ans = 0
while len(S) < N:
    min_w = INF
    u = -1
    for v in S:
        for j, w in enumerate(W[v]):
            if j not in S and w < min_w:
                min_w = w
                u = j

    ans += min_w
    S.add(u)
    
print(ans)

Python: def prim(cost):
    sumcost = 0
    V = len(cost)
    mincost = [float('inf')] * V
    used = [False] * V
    mincost[0] = 0
    while True:
        v = -1
        for u in range(V):
            if not used[u] and (v == -1 or mincost[u] < mincost[u]):
                v = u
        if v == -1: break
        used[v] = True
        sumcost = sumcost + mincost[v]
        for u in range(V):
            if cost[u][v] == -1:
                continue
            mincost[u] = min(mincost[u], cost[v][u])
    return sumcost

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))