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: n = int(input())

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

def mst():
    T = [0]
    gross_weight = 0
    cnt = n - 1
    while cnt:
        ew = 2001
        for i in range(len(T)):
            for tv, tew in enumerate(adj[T[i]]):
                if (tv not in T) and (tew != -1):
                    if tew < ew:
                        v, ew = tv, tew
        T.append(v)
        gross_weight += ew
        cnt -= 1
    print(gross_weight)


mst()

Python: from collections import deque

class Node:
    def __init__(self, val):
        self.val = val
        self.child = []

n = int(input())
g = []
# mst = [[] for _ in range(n)]
# mst = [None for _ in range(n)]

for i in range(n):
    g.append(list(map(int, input().split())))

# print(g)

for i in range(n):
    for j in range(n):
        if g[i][j] == -1:
            g[i][j] = 10**5

mst = Node(0)
# done = set()

def getClosestVertex(done):
    w = 10**10
    closest = None
    for i in done:
        for j in range(len(g[i])):
            if j in done:
                continue
            if g[i][j] < w:
                w = g[i][j]
                closest = j
    return closest, w

done = set()
done.add(0)
ans = 0

while True:
    closest, w = getClosestVertex(done)
    if closest is None:
        break
    else:
        done.add(closest)
        ans += w

print(ans)

Python: from sys import stdin
INF = 1<<21
WHITE, GRAY, BLACK = 0, 1, 2
n = int(stdin.readline())
M = [[INF] * n for _ in range(n)]
for i in range(0, n):
    for j, e in enumerate(list(map(int, stdin.readline().split()))):
        if e != -1: M[i][j] = e
d = [INF] * n
d[0] = 0
color = [False] * n
def prim():
    while True:
        minv = INF
        u = -1
        for i in range(0, n):
            if minv > d[i] and color[i] != True:
                u = i
                minv = d[i]
        if u == -1: break
        color[u] = True
        for v in range(0, n):
            if color[v] != True and d[v] > M[u][v]:
                d[v] = M[u][v]
    return sum(d)
print(prim())

Python: #coding:utf-8
inf = 1000000
n = int(input())
mtrx = []
for i in range(n):
    nums = list(map(int,input().split()))
    col = []
    for j in range(n):
        if nums[j] == -1:
            col.append(inf)
        else:
            col.append(nums[j])
    mtrx.append(col)

        
d = [inf for i in range(n)]
p = [-1 for i in range(n)]
color = ["white" for i in range(n)]
d[0] = 0
while True:
    mincost = inf
    for i in range(n):
        if color[i] != "black" and d[i] < mincost:
            mincost = d[i]
            u = i
    if mincost == inf:
        break

    color[u] = "black"
    for v in range(n):
        if color[v] != "black" and mtrx[u][v] < inf:
            if mtrx[u][v] < d[v]:
                d[v] = mtrx[u][v]
                p[v] = u
                color[v] = "gray"
print(sum(d))

Python: n = int(input())
sides = []
ws = []
ss = []
for _ in range(n):
    sides.append(list(map(int,input().split())))
for i in range(n):
    for j in range(i+1,n):
        if sides[i][j] >= 0:
            ws.append([sides[i][j],i,j])
rs = [(i) for i in range(n)]
def root(x):
    global rs
    if rs[x] == x:
        return(x)
    else:
        return(root(rs[x]))
ws.sort()
ans = 0
while(len(ws)):
    if root(ws[0][1]) != root(ws[0][2]):
        ans += ws[0][0]
        rs[root(rs[ws[0][2]])] = root(ws[0][1])
        ss.append(ws[0])
    del(ws[0])
print(ans)

Python: import heapq

def make_adj_list(v):
    adj_list = [[-1 for i in range(v)] for j in range(v)]
    return adj_list

def prim(adj_list, v, s):
    # スタートを0とする
    min_d = 0
    heap = []
    used = []
    for i in range(v):
        used.append(False)
    used[s] = True
    for i in range(v):
        if adj_list[s][i] != -1:
            heapq.heappush(heap, (adj_list[s][i], i))
        #　スタートからつなぐことができる辺をheapに入れる

    while len(heap) != 0:
        cost, to = heapq.heappop(heap)
        if used[to]:
            continue
        min_d += cost
        used[to] = True
        for i in range(v):
            if adj_list[to][i] != -1:
                heapq.heappush(heap, (adj_list[to][i], i)) 
            #集合に入れた頂点からつなぐことができる辺をheapに入れる

    return min_d

def main():
    v = int(input())
    adj_list = make_adj_list(v)
    for i in range(v):
        adj_list[i] = [int(j) for j in input().split()]
    min_d = prim(adj_list, v, 0)
    print(min_d)


if __name__ == '__main__':
    main()

Python: # -*- coding: utf-8 -*-
def prim(edges, *, start=0, adj_matrix=False, default_value=float('inf')):
    '''
    Returns the Minimum Spanning Tree(MST) of a given graph

    # sample input when given as adjacency matrix
    edges = [[0, 2, 5, 4, inf, inf],           # node 0
             [2, 0, inf, 3, 6, inf],           # node 1
             [5, inf, 0, 2, inf, 6],           # node 2
             [4, 3, 2, 0, 2, inf],             # node 3
             [inf, 6, inf, 2, 0, 4],           # node 4
             [inf, inf, 6, inf, 4, 0]]         # node 5

    # sample input when given not as adjacency matrix
    edges = [[(1, 2), (2, 5), (3, 4)],         # node 0
             [(0, 2), (3, 3), (4, 6)],         # node 1
             [(0, 5), (3, 2), (5, 6)],         # node 2
             [(0, 4), (1, 3), (2, 2), (4, 2)], # node 3
             [(1, 6), (3, 2), (5, 4)],         # node 4
             [(2, 6), (4, 4)]]                 # node 5
    '''

    n = len(edges)
    mst = []
    cost = 0
    T = [start]

    while True:
        tmp_edges = [(cost, (u, v)) for u in T for v, cost in enumerate(edges[u]) if cost != default_value and v not in T] if adj_matrix else\
                    [(cost, (u, v)) for u in T for v, cost in edges[u] if v not in T]

        if tmp_edges:
            min_cost, min_edge = min(tmp_edges)
            mst.append(min_edge)
            cost += min_cost
            T.append(min_edge[1])

        else:
            if len(mst) != n - 1:
                raise NoSpanningError(
                    'There is no spanning tree in this graph (search started from node{})'.
                    format(start))

            else:
                return mst, cost


class NoSpanningError(Exception):
    pass


if __name__ == '__main__':
    '''
    an example of using this function
    AIZU ONLINE JUDGE - ALDS_1_12_A
    '''

    n = int(input())
    edges = [[int(cost) if int(cost) != -1 else float('inf') for cost in input().split()] for i in range(n)]

    print(prim(edges, adj_matrix=True)[1])