Go: package main

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

// I/O
type Scanner struct {
	sc *bufio.Scanner
}

func NewScanner() *Scanner {
	sc := bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)
	sc.Buffer(make([]byte, 1024), int(1e+9))
	return &Scanner{sc}
}

func (s *Scanner) nextStr() string {
	s.sc.Scan()
	return s.sc.Text()
}

func (s *Scanner) nextInt() int {
	i, e := strconv.Atoi(s.nextStr())
	if e != nil {
		panic(e)
	}
	return i
}

func (s *Scanner) nextFloat() float64 {
	f, e := strconv.ParseFloat(s.nextStr(), 64)
	if e != nil {
		panic(e)
	}
	return f
}

func (s *Scanner) nextRuneSlice() []rune {
	return []rune(s.nextStr())
}

func (s *Scanner) nextIntSlice(n int) []int {
	res := make([]int, n)
	for i := 0; i < n; i++ {
		res[i] = s.nextInt()
	}
	return res
}

func (s *Scanner) nextFloatSlice(n int) []float64 {
	res := make([]float64, n)
	for i := 0; i < n; i++ {
		res[i] = s.nextFloat()
	}
	return res
}

// Arithmetic
func max(nums ...int) int {
	m := nums[0]
	for _, i := range nums {
		if m < i {
			m = i
		}
	}
	return m
}

func min(nums ...int) int {
	m := nums[0]
	for _, i := range nums {
		if m > i {
			m = i
		}
	}
	return m
}

func abs(x int) int {
	if x > 0 {
		return x
	}
	return -x
}

func pow(x, y int) int {
	res := 1
	for i := 0; i < y; i++ {
		res *= x
	}
	return res
}

func ceil(a, b int) int {
	if a%b == 0 {
		return a / b
	} else {
		return a/b + 1
	}
}

// Sort
type RuneSlice []rune

func (a RuneSlice) Len() int           { return len(a) }
func (a RuneSlice) Less(i, j int) bool { return a[i] < a[j] }
func (a RuneSlice) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }

const INF = 1 << 60

// Main
func main() {
	sc := NewScanner()
	wtr := bufio.NewWriter(os.Stdout)
	N := sc.nextInt()
	G := make([][]int, N)
	for i := 0; i < N; i++ {
		G[i] = make([]int, N)
		for j := 0; j < N; j++ {
			G[i][j] = sc.nextInt()
		}
	}
	d := make([]int, N)
	for i := 0; i < N; i++ {
		d[i] = INF
	}
	seen := make([]bool, N)
	d[0] = 0
	ans := 0
	for {
		cur := 0
		minCost := INF
		for i := 0; i < N; i++ {
			if !seen[i] && d[i] < minCost {
				minCost = d[i]
				cur = i
			}
		}
		if minCost == INF {
			break
		}
		seen[cur] = true
		ans += d[cur]
		for i := 0; i < N; i++ {
			cost := G[cur][i]
			if cost != -1 && cost < d[i] {
				d[i] = cost
			}
		}
	}

	fmt.Fprintln(wtr, ans)
	wtr.Flush()
}

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)