Go: package main

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

const (
	MAX_N      = 200
	MAX_WEIGHT = 2000
)

type Edge struct {
	start  int
	end    int
	weight int
}

type ShortestInfo struct {
	edges    []Edge
	shortest int
}

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

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

	shortestList := make([]ShortestInfo, n)
	for i := 1; i < n; i++ {
		shortestList[i] = ShortestInfo{edges: []Edge{}, shortest: MAX_N*MAX_WEIGHT + 1}
	}

	adjacentMatrix := make([][]int, n)
	for i := 0; i < n; i++ {
		adjacentMatrix[i] = make([]int, n)
		for j := 0; j < n; j++ {
			v, err := nextInt(sc)
			if err != nil {
				panic(err)
			}
			adjacentMatrix[i][j] = v
		}
	}

	mst([]int{1}, shortestList, adjacentMatrix)
	fmt.Println(shortestList)
	fmt.Println(calculateMinWeight(shortestList))
}

func calculateMinWeight(shortestList []ShortestInfo) int {
	visitedList := make([]bool, len(shortestList))
	visitedList[0] = true
	sumWeight := 0
	for !visitedAll(visitedList) {
		shortestInfo := shortestList[0]
		shortestList = shortestList[1:]
		edges := shortestInfo.edges
		for _, edge := range edges {
			if !visitedList[edge.end-1] {
				visitedList[edge.end-1] = true
				sumWeight += edge.weight
			}
		}
	}
	return sumWeight
}

func visitedAll(visitedList []bool) bool {
	for _, v := range visitedList {
		if !v {
			return false
		}
	}
	return true
}

func mst(nodeStack []int, shortestList []ShortestInfo, adjacentMatrix [][]int) {
	for len(nodeStack) > 0 {
		currentNode := nodeStack[0]
		nodeStack = nodeStack[1:]
		currentShortest := getShortest(currentNode, shortestList)
		adjacents := findAdjacents(currentNode, adjacentMatrix)
		for i := 0; i < len(adjacents); i++ {
			adj := adjacents[i]
			s := getShortest(adj.end, shortestList)
			if currentShortest.shortest+adj.weight < s.shortest || (currentShortest.shortest+adj.weight == s.shortest && len(currentShortest.edges)+1 > len(s.edges)) {
				setShortest(adj.end, adj, currentShortest, shortestList)
				nodeStack = append(nodeStack, adj.end)
			}
		}
	}
}

func getShortest(node int, shortestList []ShortestInfo) ShortestInfo {
	return shortestList[node-1]
}

func setShortest(node int, edge Edge, currentShortest ShortestInfo, shortestList []ShortestInfo) {
	newEdges := make([]Edge, len(currentShortest.edges)+1)
	for i := 0; i < len(newEdges)-1; i++ {
		newEdges[i] = currentShortest.edges[i]
	}
	newEdges[len(newEdges)-1] = edge
	shortestInfo := ShortestInfo{edges: newEdges, shortest: currentShortest.shortest + edge.weight}
	shortestList[node-1] = shortestInfo
}

func findAdjacents(currentNode int, adjacentMatrix [][]int) []Edge {
	adjacents := adjacentMatrix[currentNode-1]
	edges := []Edge{}
	for i, v := range adjacents {
		if v > 0 {
			edges = append(edges, Edge{start: currentNode, end: i + 1, weight: v})
		}
	}
	return edges
}

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

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