Go: package main

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

var scanner = bufio.NewScanner(os.Stdin)

func nextString() string {
	scanner.Scan()
	return scanner.Text()
}

func nextInt() int {
	n, err := strconv.Atoi(nextString())
	if err != nil {
		fmt.Printf("strconv.Atoi failed: %v\n", err)
	}
	return n
}

type ElementKey int
type Node struct {
	key    ElementKey
	parent *Node
	rank   int
}

func newNode(key ElementKey) *Node {
	node := Node{}
	node.key = key
	node.parent = &node
	node.rank = 0

	return &node
}

func union(x, y *Node) {
	xSet := findSet(x)
	ySet := findSet(y)
	link(xSet, ySet)
}

func link(x, y *Node) {
	if x.rank > y.rank {
		y.parent = x
	} else {
		x.parent = y

		if x.rank == y.rank {
			y.rank++
		}
	}
}

func findSet(x *Node) *Node {
	if x != x.parent {
		x.parent = findSet(x.parent)
	}
	return x.parent
}

func newDisjointSets(nSets int) *DisjointSets {
	sets := DisjointSets{}
	sets.keyToNode = map[ElementKey]*Node{}
	for i := 0; i < nSets; i++ {
		key := ElementKey(i)
		sets.keyToNode[key] = newNode(key)
	}
	return &sets
}

type DisjointSets struct {
	keyToNode map[ElementKey]*Node
}

func (sets *DisjointSets) union(x, y ElementKey) {
	xNode := sets.keyToNode[x]
	yNode := sets.keyToNode[y]
	union(xNode, yNode)
}

func (sets DisjointSets) findSet(x ElementKey) *Node {
	xNode := sets.keyToNode[x]
	return findSet(xNode)
}

type Edge struct {
	i, j   int
	weight int
}

func main() {
	scanner.Split(bufio.ScanWords)

	n := nextInt()
	sets := newDisjointSets(n)
	edges := []Edge{}
	a := make([][]int, n)
	for i := 0; i < n; i++ {
		a[i] = make([]int, n)
		for j := 0; j < n; j++ {
			a[i][j] = nextInt()
			if a[i][j] >= 0 {
				e := Edge{
					i:      i,
					j:      j,
					weight: a[i][j],
				}
				edges = append(edges, e)
			}
		}
	}
	sort.Slice(edges, func(i, j int) bool { return edges[i].weight < edges[j].weight })
	totalWeight := 0
	for _, edge := range edges {
		i := ElementKey(edge.i)
		j := ElementKey(edge.j)
		if sets.findSet(i) != sets.findSet(j) {
			totalWeight += edge.weight
			sets.union(i, j)
		}
	}
	fmt.Println(totalWeight)
}

Python: from heapq import heappush, heappop, heapify
from typing import List, Tuple


if __name__ == "__main__":
    num_vertices = int(input())
    adj_list: List[List[Tuple[int, int]]] = [[] for _ in range(num_vertices)]

    for vertex in range(num_vertices):
        for adj, cost in enumerate(map(lambda x: int(x), input().split())):
            if -1 != cost:
                # Store values as (cost, adj) to aplly heapify to cost values.
                adj_list[vertex].append((cost, adj))

    visited: List[bool] = [False] * num_vertices
    # Set the root node.
    que = [(cost, adj) for cost, adj in adj_list[0]]
    visited[0] = True
    heapify(que)

    total_cost = 0
    while [] != que:
        cost, adj = heappop(que)
        if visited[adj]:
            continue
        visited[adj] = True
        total_cost += cost
        for n_cost, n_adj in adj_list[adj]:
            if visited[n_adj]:
                continue
            heappush(que, (n_cost, n_adj))

    print(total_cost)

Python: import heapq

n = int(input())
A = [[int(i) for i in input().split()] for i in range(n)]
h = []
DP = {}
heapq.heappush(h,(0,0))
c = 0
while(len(DP)<n):
    tmp = heapq.heappop(h)
    if tmp[1] in DP:
        continue
    c += tmp[0]
    DP[tmp[1]] = 1
    for i,j in enumerate(A[tmp[1]]):
        if j > -1 and not i in DP:
            heapq.heappush(h,(j,i))
print(c)

Python: n=int(input())
inf=10000
color=["white" for i in range(n)]
p=[-1 for i in range(n)]
d=[inf for i in range(n)]
M=[[] for i in range(n)]


for i in range(n):
    tmp=list(map(int,input().split()))
    for j in range(n):
        if tmp[j]==-1:
            M[i].append(inf)
        else:
            M[i].append(tmp[j])

def prim():
    d[0]=0
    while True:
        mincost=inf
        for i in range(n):
            if mincost>d[i] and color[i]!="black":
                mincost=d[i]
                u=i
        if mincost==inf:
            break
        color[u]="black"
        for j in range(n):
            if color[j]!="black" and M[u][j]!=inf:
                if M[u][j]<d[j]:
                    d[j]=M[u][j]
                    p[j]=u
                    color[j]="gray"

prim()
print(sum(d))

Python: import heapq
from collections import defaultdict
v_num = int(input())
edges = defaultdict(list)
for i in range(v_num):
    data = [int(n) for n in input().split(" ")[1:]]
    for j in range(i + 1, v_num):
        if data[j] != -1:
            edges[i].append([data[j], j])
            edges[j].append([data[j], i])
queue = []
heapq.heapify(queue)
for c in edges[0]:
    heapq.heappush(queue, c)
visited = {0}
answer = 0
while len(visited) < v_num:
    q = heapq.pop(queue)
    weight, one = q[0], q[1]
    if one in visited:
        continue
    answer += weight
    for e in edges[one]:
        heapq.heappush(queue, e)
    visited |= {one}
print(answer)

Python: N = int(input())
G = [[] for i in range(N)]
for v in range(N):
    for w, c in enumerate(map(int, input().split())):
        if c != -1:
            G[v].append((w, c))

from heapq import heappush, heappop, heapify
used = [0]*N
que = [(c, w) for w, c in G[0]]
used[0] = 1
heapify(que)

ans = 0
while que:
    cv, v = heappop(que)
    if used[v]:
        continue
    used[v] = 1
    ans += cv
    for w, c in G[v]:
        if used[w]:
            continue
        heappush(que, (c, w))
print(ans)

Python: def memoize(f):  
    cache = {}  
    def helper(x):  
        if x not in cache:              
            cache[x] = f(x)  
        return cache[x]  
    return helper 

def split_apex(a):
    if len(a) == 2:
        yield (a[0],), (a[1],)
    else:
        for i in range(0, len(a)):
            yield (a[i],), a[:i] + a[i + 1:]

@memoize
def wait(a):
    global g
    if len(a) == 1:
        return 0
    return min(calc_wait(apex, apices) for apex, apices in split_apex(a))

def calc_wait(apex, apices):
    global g
    w = [g[apex[0]][i] for i in apices if g[apex[0]][i] != -1]
    return  wait(apex) + wait(apices) + (min(w) if len(w) else 200000)

n = int(input())
g = [None] + [[None] + list(map(int, input().split())) for _ in range(n)]

a = tuple(i + 1 for i in range(n))
wait(a)

Python: 
import heapq

def main():

    INF = 1000000009
    n = int(input())
    e = [[] for _ in range(n)]
    for i in range(n):
        inf = list(map(int,input().split()))
        for j in range(n):
            if inf[j]!=-1:e[i].append([j,inf[j]])

    dp = [INF]*n
    finished = [False]*n
    dp[0] = 0
    pq = [[0,0]]
    heapq.heapify(pq)
    while pq:
        cost,v = heapq.heappop(pq)
        if dp[v]<cost:continue
        finished[v] = True
        for i in range(len(e[v])):
            u = e[v][i][0]
            ncost = e[v][i][1]
            if ncost < dp[u] and not finished[u]:
                dp[u] = ncost
                heapq.heappush(pq,[ncost,u])
    res = 0
    for i in range(n):res+=dp[i]
    print(res)


if __name__ == '__main__':
    main()

Python: 

WHITE = 0
GRAY = 1
BLACK = 2

INF = 2000000000

def prim():
    d[0] = 0
    p[0] = -1
    
    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 m[u][v] != -1:
                if m[u][v] < d[v]:
                    d[v] = m[u][v]
                    p[v] = u
                    color[v] = GRAY
            

n = int(input())

m = [[0 for i in range(n)] for j in range(n)]
for i in range(n):
    nums=list(map(int,input().split()))
    for j in range(n):
        m[i][j] = nums[j]

color = [WHITE] * n
d = [INF] * n
p = [-1] * n


prim()

sum = 0
for i in range(n):
    sum += d[i]

print(sum)