Go: package main

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

// Define disjoint-set forests

type vertexNo int

type vertex struct {
	number vertexNo
	rank int
	parent *vertex
}

func makeSet(number vertexNo) vertex {
	return vertex {
		number: number,
		rank: 0,
		parent: nil,
	}
}

func union(x, y *vertex) *vertex {
	return link(findSet(x), findSet(y))
}

func link(x, y *vertex) *vertex {
	if x.rank > y.rank {
		y.parent = x
		return x
	} else {
		x.parent = y
		if x.rank == y.rank {
			y.rank += 1
		}
		return y
	}
}

func findSet(v *vertex) *vertex {
	if v.parent == nil {
		return v
	}
	v.parent = findSet(v.parent)
	return v.parent
}

// Function to calculate minimum spanning tree

type matrix [][]int

type edge struct {
	one vertexNo
	two vertexNo
	weight int
}

const(
	MAX_VERTICES = 100
)

func newEdgesFromMatrix(matrix matrix) []edge {
	edges := make([]edge, 0, MAX_VERTICES * MAX_VERTICES)

	for i := 0; i < len(matrix); i++ {
		row := matrix[i]
		for j := i; j < len(row); j++ {
			if row[j] >= 0 {
				edge := edge{one: vertexNo(i+1), two: vertexNo(j+1), weight: row[j]}
				edges = append(edges, edge)
			}
		}
	}

	return edges
}

func solve(matrix matrix) int {
	nVertices := len(matrix)

	// initialize vertices
	vertices := make([]vertex, nVertices)
	for i := 0; i < nVertices; i++ {
		vertices[i] = makeSet(vertexNo(i+1))
	}

	// prepare edges sorted in the ascending order of weight
	edges := newEdgesFromMatrix(matrix)
	sort.Slice(edges, func(i, j int) bool {
		return edges[i].weight < edges[j].weight
	})

	unionCount := 0
	weightSum := 0
	for unionCount < nVertices-1 {
		for i := 0; i < len(edges); i++ {
			edge := edges[i]
			v1 := &vertices[edge.one-1]
			v2 := &vertices[edge.two-1]
			rep1 := findSet(v1)
			rep2 := findSet(v2)
			if rep1.number == rep2.number {
				continue
			}
			union(rep1, rep2)
			edges = append(edges[0:i], edges[i+1:]...)
			weightSum += edge.weight
			unionCount++
			break
		}
	}

	return weightSum
}

// main

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

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

	matrix := parseMatrix(n, sc)

	edges := newEdgesFromMatrix(matrix)
	sort.Slice(edges, func(i, j int) bool {
		return edges[i].weight < edges[j].weight
	})

	fmt.Println(solve(matrix))
}

func parseMatrix(n int, sc *bufio.Scanner) [][]int {
	matrix := make([][]int, n)
	for i := 0; i < n; i++ {
		matrix[i] = make([]int, n)
		for j := 0; j < n; j++ {
			x, err := nextInt(sc)
			if err != nil {
				panic(err)
			}
			matrix[i][j] = x
		}
	}
	return matrix
}

func nextText(sc *bufio.Scanner) string {
	sc.Scan()
	return sc.Text()
}

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

Python: #!/usr/bin/python3
import itertools

n = int(input())
A = []
for i in range(n):
    src = input()
    dst = src.replace('-1', '3000')
    ai = list(map(int, dst.split()))
    A.append(ai)
# rand
i = 0
S = 0
G = set()
T = set(range(n))

T.remove(i)
G.add(i)

while len(T) > 0:
    m = 3000
    mg = None
    mt = None
    for g, t in itertools.product(G, T):
        if A[g][t] < m:
            mg = g
            mt = t
            m = A[g][t]
    S += m
    G.add(mt)
    T.remove(mt)

print(S)

Python: import array
import collections
import heapq

INF = 1e9

N = int(input())

AdjacentVertex = collections.namedtuple('AdjacentVertex', 'vertex cost')
adjacency_list = collections.defaultdict(set)

NO_VERTEX = -1
 
def compute_mst_prim(max_v, adj_list):
    pred = collections.defaultdict(lambda: NO_VERTEX)
    key = collections.defaultdict(lambda: INF)
    key[0] = 0
    pq = [(key[v], v) for v in range(max_v)]
    heapq.heapify(pq)
    in_pq = array.array("B", (True for _ in range(max_v)))
    while pq:
        _, u = heapq.heappop(pq)
        in_pq[u] = False
        for v, v_cost in adj_list[u]:
            if in_pq[v]:
                weight = v_cost
                if weight < key[v]:
                    pred[v] = u
                    key[v] = weight
                    heapq.heappush(pq, (weight, v))
                    in_pq[v] = True
    return (pred, key)

for i in range(N):
    u = list(map(int, input().split()))
    for j in range(N):
        if u[j] == -1:
            adjacency_list[i].add(AdjacentVertex(j, INF))
            adjacency_list[j].add(AdjacentVertex(i, INF))
        else:
            adjacency_list[i].add(AdjacentVertex(j, u[j]))
            adjacency_list[j].add(AdjacentVertex(i, u[j]))

(_, key) = compute_mst_prim(N, adjacency_list)

print(sum(key.values()))

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]:
        if e[1] not in visited:
            heapq.heappush(queue, e)
    visited |= {one}
print(answer)

Python: import sys
INF = float('inf')
n = int(input())
adja_matrix = [[int(i) for i in line.split()] for line in sys.stdin.read().splitlines()]
condition = ['INIT'] * n
distance = [INF] * n
p = [0] * n
distance[0] = 0
p[0] = -1

while True:
    mincost = INF
    for i in range(n):
        if condition[i] != 'FINISH' and distance[i] < mincost:
            mincost = distance[i]
            u = i

    if mincost == INF:
        break

    condition[u] = 'FINISH'

    for v in range(n):
        if condition[i] != 'FINISH' and adja_matrix[u][v] != -1:
            if adja_matrix[u][v] < distance[v]:
                distance[v] = adja_matrix[u][v]
                p[v] = u
                condition[v] = 'CHECK'

sum = 0
for i in range(n):
    if p[i] != -1:
        sum += adja_matrix[i][p[i]]

print(sum)

Python: import heapq


def prim(G):
    n = len(G)
    is_visited = [False for _ in range(n)]
    que = []
    heapq.heappush(que, (0, 0))

    ret = 0
    while que:
        cost, cur_v = heapq.heappop(que)
        if is_visited[cur_v]:
            continue

        is_visited[cur_v] = True
        ret += cost
        for (adj_dst, adj_cost) in G[cur_v]:
            heapq.heappush(que, (adj_cost, adj_dst))

    return ret


def main():
    n = int(input())
    g = [[] for _ in range(n)]
    a = [[int(x) for x in input().split()] for _ in range(n)]

    for i in range(n):
        for j in range(n):
            if a[i][j] == -1:
                continue
            g[i].append((j, a[i][j]))
            g[j].append((i, a[i][j]))

    print(prim(g))


main()

Python: n = int(input())
M = [list(map(int, input().split())) for _ in range(n)]

WHITE = 0
GREY = 1
BLACK = 2
INFTY = 10**10

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


def prim():
    # すべての頂点u について color[u] をwhiteとして、d[u]をINFINITYへ
    d[0] = 0
    p[0] = -1  # 親なし

    while True:
        mincost = INFTY
        for i in range(0, n):
            if color[i] != BLACK and d[i] < mincost:
                # まだ未訪問でコストが最小になるところを探す。
                # WHITEなところはd[i]=INFTYなので来ない
                mincost = d[i]
                # 最小コストになる場所を見つける
                u = i
                # 訪れる場所を決定
        if mincost == INFTY:
            break

        color[u] = BLACK
        # 起点座標の決定

        for v in range(0, 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] = GREY


prim()
print(sum(d))