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: import sys
from collections import defaultdict

def push_vertex(vtx: int,queue: list, weights: dict, done: dict):
    queue.extend(weights[vtx])
    done[vtx] = True
    [queue.remove(x) for x in queue[:] if done[x[0]]]
    del weights[vtx]
    queue.sort(key=lambda x: x[1], reverse=True)
    return


def main():
    n = int(input())
    weights = defaultdict(list)
    for i in range(n):
        for idx, weight in enumerate(input().split()):
            if weight != '-1':
                weights[i+1].append((idx+1, int(weight)))
    done = {}
    for i in weights.keys():
        done[i] = False
    mst_weights = 0
    queue = []
    vtx = [*weights][0]
    push_vertex(vtx, queue, weights, done)

    while len(weights) != 0:
        new_vtx, new_vtx_weight = queue.pop()
        mst_weights += new_vtx_weight
        #print(f"connect to {new_vtx} ,weight={new_vtx_weight}")
        push_vertex(new_vtx, queue, weights, done)

    print(mst_weights)
    return

main()

Python: MAX = 100
INF = 1 << 21
WHITE = 0 # ?????¢?´¢
GRAY = 1  # ??¢?´¢????±?
BLACK = 2 # ??¢?´¢??????

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

for i in range(n):
    for j in range(n):
        if M[i][j] == -1:
            M[i][j] = INF

d = [INF for i in range(n)] # ??¢?´¢????±?
p = [-1 for i in range(n)]  # ??????????????????
color = [WHITE for i in range(n)]

def prim():
    global M, d, p, color

    d[0] = 0

    while(1):
        minv, u = INF, -1
        for i in range(n):
            if minv > d[i] and color[i] != BLACK:
                u = i
                minv = d[i]
        if u == -1:
            break
        color[u] = BLACK # ??¢?´¢???????????´??°
        for v in range(n):
            if color[v] != BLACK and M[u][v] != INF:
                if d[v] > M[u][v]:
                    d[v], p[v], color[v] = M[u][v], u, GRAY
    return sum([M[i][p[i]] for i in range(n) if p[i] != -1])


print(prim())

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: N = int(input())
P = [i for i in range(N)]
weight = []

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)
    
# まずは辺の重さをソートするために辺の重さの配列を作りましょう→マイナス1は除外
for i in range(N):
    lis = list(map(int,input().split()))
    for j in range(N):
        if lis[j] == -1:
            continue
        else:
            weight.append([lis[j],i,j])
# ソートされた順に小さい順から次々とuniteして行こう
weight.sort()
length = len(weight)
k = 0
total_weight = 0

for k in range(length):
    if is_same_set(weight[k][1],weight[k][2]):
        continue
    else:
        unite(weight[k][1],weight[k][2])
        total_weight += weight[k][0]

print(total_weight)
    
# その際にもし付け加えてis_same_set(x,y)がtrueだったらやめよう

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

for i in range(n):

    line = list(map(int, input().split()))

    for i in range(len(line)):
        if line[i] == -1:
            line[i] = infinity
    a.append(line)

checked = [False] * n
d = [infinity] * n
checked[0] = True
ansswer = 0
next = 0

for i in range(n - 1):
    for j in range(n):
        if a[next][j] < d[j]:
            d[j] = a[next][j]

    minimumNeightbor = 0
    minimumWeight = infinity

    for j in range(n):
        if not checked[j] and d[j] < minimumWeight:
            minimumNeightbor = j
            minimumWeight = d[j]

    checked[minimumNeightbor] = True
    next = minimumNeightbor
    ansswer += minimumWeight

print(ansswer)

Python: INF = float("inf")
def MAIN():
    n = int(input())
    M = [[INF] * 101 for _ in range(101)]
    for i in range(n):
        for j, e in enumerate(map(int, input().split())):
            if e != -1:
                M[i][j] = e
    def prim():
        d = [INF] * n
        t = [-1] * n
        color = [0] * n
        d[0] = 0
        while True:
            minv = INF
            u = -1
            for i in range(n):
                if minv > d[i] and color[i] != 2:
                    u = i
                    minv = d[i]
            if u == -1:
                break
            color[u] = 2
            for v in range(n):
                if color[v] != 2 and d[v] > M[u][v]:
                    d[v] = M[u][v]
                    t[v] = u
                    color[v] = 1
        return sum(d)
    print(prim())
MAIN()