Go: package main

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

const (
	MAX = 100
	INF = 1 << 21
	WHITE = 0
	GRAY = 1
	BLACK = 2
)

var (
	n int
	M [MAX][MAX]int
)

func prim() int {
	var u, minv int
	var d [MAX]int
	var p [MAX]int
	var color [MAX]int

	for i := 0; i < n; i++ {
		d[i] = INF
		p[i] = -1
		color[i] = WHITE
	}
	d[0] = 0
	for {
		minv = INF
		u = -1
		for i := 0; i < n; i++ {
			if minv > d[i] && color[i] != BLACK {
				u = i
				minv = d[i]
			}
		}
		if u == -1 {
			break
		}
		color[u] = BLACK
		for v := 0; v < n; v++ {
			if color[v] != BLACK && M[u][v] != INF {
				if d[v] > M[u][v] {
					d[v] = M[u][v]
					p[v] = u
					color[v] = GRAY
				}
			}
		}
	}
	sum := 0
	for i := 0; i < n; i++ {
		if p[i] != -1 {
			sum += M[i][p[i]]
		}
	}
	return sum
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	scanner.Scan()
	n, _ = strconv.Atoi(scanner.Text())
	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			scanner.Scan()
			e, _ := strconv.Atoi(scanner.Text())
			if e == -1 {
				M[i][j] = INF
			} else {
				M[i][j] = e
			}
		}
	}
	fmt.Println(prim())
}

Python: 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
 
#!/usr/bin/env python
from __future__ import division, print_function
from sys import stdin, maxint
 
 
def main():
    num = int(stdin.readline())
 
    M = []
    for _ in xrange(num):
        M.append([int(s) for s in stdin.readline().split()])
 
    g = set(xrange(1, num+1))
    index = g.pop()
    h = {index}
    weight = 0
 
    while g:
        minimum = maxint
        for j in h:
            mj = M[j-1]
            for i in g:
                if 0 <= mj[i-1] < minimum:
                    index = i
                    minimum = mj[i-1]
        h.add(index)
        g.remove(index)
        weight += minimum
 
    print(weight)

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))