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: # -*- 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 not as adjacency list (generally works faster)
    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

    # 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
    '''

    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 = [[(j, int(cost)) for j, cost in enumerate(input().split()) if int(cost) != -1] for i in range(n)]

    print(prim(edges)[1])

Python: import sys
# sys.stdin = open('input.txt')

def createMatrix():
  matrix = [[i for i in map(int, input().split())] for i in range(n)]
  return matrix

def prim():
    d[0] = 0
    p[0] = -1

    while True:
        mincost = INFTY
        for i in range(n):
            if status[i] != VISITED and d[i] < mincost:
                mincost = d[i]
                u = i

        if mincost == INFTY:
            break

        status[u] = VISITED

        for v in range(n):
            if status[v] != VISITED and matrix[u][v] != -1:
                if matrix[u][v] < d[v]:
                    d[v] = matrix[u][v]
                    p[v] = u
                    status[v] = VISITING

n = int(input())
NOT_VISITED = 0 # WHITE
VISITING = 1 # GRAY
VISITED = 2 # BLACK
INFTY = 10**21

matrix = createMatrix()
status =  [NOT_VISITED] * n
d = [INFTY] * n
p = [-1] * n

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.heappop(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):
    G.append(input().split())
    for j in range(len(G[i])):
        G[i][j] = int(G[i][j])

ans = 0
mincost = [2001] * n
flag = [0] * n
mincost[0] = 0
while True:
    v = -1
    for j in range(n):
        if flag[j] != 1 and (v == -1 or mincost[j] < mincost[v]):
            v = j
    if v == -1:
        break
    flag[v] = 1
    ans += mincost[v]
    for j in range(n):
        if G[v][j] == -1: continue
        mincost[j] = min(mincost[j], G[v][j])

print(ans)

Python: n = int(input())
G = [[int(i) for i in input().split()] for i in range(n)]

S = set([])
for i,row in enumerate(G):
    for j,col in enumerate(row):
        if col != -1:
            k = tuple(sorted([i,j]))
            S.add(k + (col, ))

rank = {}
p = {}

def makeSet(x):
    p[x] = x
    rank[x] = 0

def link(x, y):
    if  rank[x] > rank[y]:
        p[y] = x
    else:
        p[x] = y
    if  rank[x] == rank[y]:
        rank[y] += 1

def union(x, y):
    link(findSet(x), findSet(y))
    
def findSet(x):
    if  x != p[x]:
        p[x] = findSet(p[x])
    return p[x]
    
def isSameSet(x, y):
    return findSet(x) == findSet(y)

def kruskal(G, n, S):
    ret = 0
    for x in range(n):
        makeSet(x)
    while len(S) != 0:
        u, v, c = min(S, key=lambda x: x[2])
        S = S - set([(u,v,c)])
        if not isSameSet(u, v):
            union(u, v)
            ret += c
    return ret
print(kruskal(G, n, S))

Python: n = int(input())
a = []

for i in range(n):
    inp = input()
    if "-1" in inp:
        inp = inp.replace("-1","10000")
    a.append(list(map(int, inp.split())))

w = 0
v = set()
v.add(0)

while len(v) < n:
    print(v)
    min_w   = 10000
    min_idx = 0
    i = 0
    for node in v:
        if min_w > min(a[node]):
            min_w = min(a[node])
            i = node
            min_idx = a[i].index(min_w)
    if min_idx in v:
        a[i][min_idx] = 10000
        continue
    else:
        w += min_w
        v.add(min_idx)

print(w)