Go: package main

import (
	"bufio"
	"fmt"
	"log"
	"math"
	"os"
	"strconv"
	"strings"
)

type color int

const (
	white color = iota // 未訪問
	mst                // MSTとして確定
)

// 頂点
type node struct {
	matrix   []int // 隣接行列
	minToMst int   // MSTへの重み最小値
	parent   int   // 最小値の相手
	color    color
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	n := eGetInt(scanner)

	nodes := make([]node, n)
	for i := 0; i < n; i++ {
		nodes[i].matrix = eAtoi((strings.Fields(eGetline(scanner))))
		nodes[i].parent = -1
		nodes[i].minToMst = math.MaxInt16
		nodes[i].color = white
	}

	// 初回はnode[0]がMSTに入るように,minToMstを設定
	nodes[0].minToMst = 0
	for { // 全部チェックするまで

		// どの頂点を新たにMSTに取り込むか
		min := math.MaxInt16
		u := -1
		for i := 0; i < n; i++ {
			if nodes[i].color == mst {
				continue
			}
			if nodes[i].minToMst < min {
				u = i
				min = nodes[i].minToMst
			}
		}

		if u == -1 {
			break
		}
		// MSTに追加する頂点決定
		nodes[u].color = mst

		// MSTに属していない頂点それぞれについて,MSTとの最小の重みを更新
		for i := 0; i < n; i++ {
			if nodes[i].color == mst {
				continue
			}
			if nodes[i].matrix[u] == -1 {
				// 接してない
				continue
			}
			if nodes[i].matrix[u] < nodes[i].minToMst {
				// node[u]との重みが最小
				nodes[i].minToMst = nodes[i].matrix[u]
				nodes[i].parent = u
			}
		}
	}

	sum := 0
	for _, v := range nodes {
		// node[0]はparentが入っていない
		if v.parent != -1 {
			sum += v.matrix[v.parent]
		}
	}
	fmt.Println(sum)
}

func eGetInt(scanner *bufio.Scanner) int {
	t := eAtoi(strings.Fields(eGetline(scanner)))
	return t[0]
}

func eGetline(p *bufio.Scanner) string {
	if !p.Scan() {
		if err := p.Err(); err != nil {
			log.Fatal(err.Error())
		}
		return ""
	}
	return p.Text()
}

func eAtoi(s []string) []int {
	ints := make([]int, len(s))
	var err error
	for i, e := range s {
		ints[i], err = strconv.Atoi(e)
		if err != nil {
			log.Fatal(err.Error())
		}
	}
	return ints
}

Python: n = int(input())
sides = []
ws = []
for _ in range(n):
    sides.append(list(map(int,input().split())))
for i in range(n):
    for j in range(i+1,n):
        if sides[i][j] > 0:
            ws.append([sides[i][j],i,j])
rs = [i for i in range(n)]
def root(x):
    global rs
    if rs[x] == x:
        return(x)
    else:
        return(root(rs[x]))
ws.sort()
ans = 0
while(len(ws)):
    if root(ws[0][1]) != root(ws[0][2]):
        ans += ws[0][0]
        rs[root(rs[ws[0][2]])] = root(ws[0][1])
    del(ws[0])
print(ans)

Python: N = 100
INF = float('inf')
M = [[INF for _ in range(N)] for _ in range(N)]
n = 0
WHITE = 0
GRAY = 1
BLACK = 2
color = [WHITE for _ in range(N)]
d = [INF for _ in range(N)]
p = [0 for _ in range(N)]


def main():
    global N
    n = int(input())
    for i in range(n):
        a_s = list(map(int, input().split(' ')[1:]))
        for j in range(n):
            if a_s[j] != -1:
                M[i][j] = M[j][i] = a_s[j]
    print(prim(n))


def prim(n):
    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] < INF:
                if M[u][v] < d[v]:
                    d[v] = M[u][v]
                    p[v] = u
                    color[v] = GRAY
    return sum(d[:n])


if __name__ == '__main__':
    main()

Python: #!/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)


main()

Python: N = int(input())

a = [list(map(int, input().split())) for _ in range(N)]

vis = [False] * N
inf = 1e9
d = [inf] * N
d[0] = 0
cost = 0
for _ in range(N):
    nv, ni = inf, -1
    for i in range(N):
        if not vis[i] and d[i] < nv:
            nv, ni = d[i], i
    vis[ni] = True
    cost += nv
    for i in range(N):
        c = a[ni][i]
        if c > -1:
            d[i] = min(d[i], c)
print(cost)

Python: class Forest:
    def __init__(self, g, id):
        self.forest = set([id])
        self.graph = g
        self.next_wait = self.graph[id]
        self.wait = 0
    def add_tree(self, id):
        self.wait += self.next_wait[id]
        self.forest.update([id])
        
        self.marge_next_wait(id)
    def next_tree(self):
        min_id = min_wait = None
        for id, wait in self.next_wait.items():
            if id not in self.forest:
                if min_wait == None or min_wait > wait:
                    min_wait = wait
                    min_id = id
        return min_id
    def marge_next_wait(self, merge_id):
        for id, wait in self.graph[merge_id].items():
            if id not in self.next_wait or self.next_wait[id] > wait:
                self.next_wait[id] = wait
n = int(input())
g = [{e:i for e, i in enumerate(map(int, input().split())) if i != -1} for _ in range(n)]
forest = Forest(g,0)
for i in range(4):
    id = forest.next_tree()
    forest.add_tree(id)
print(forest.wait)

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

class Node:
    def __init__(self, n):
        self.data = n
        self.parent = self
        self.rank = 0
    def find(self):
        if self.parent.data == self.data:
            return self
        else:
            ret = self.parent.find()
            self.parent = ret
            return ret
    def union(self, rhs):
        lhs = self
        lhs_root = lhs.find()
        rhs_root = rhs.find()
        if lhs_root.rank > rhs_root.rank:
            rhs_root.parent = lhs
        elif rhs_root.rank > lhs_root.rank:
            lhs_root.parent = rhs
        elif lhs_root.data != rhs_root.data:
            lhs_root.parent = rhs_root
            rhs_root.rank += 1
    def is_same(self, rhs):
        lhs = self
        return lhs.find().data == rhs.find().data

V = [Node(i) for i in range(n)]
inf = 2005

for i in range(n):
    for j in range(n):
        E[i][j] = [E[i][j], i, j, 0 if E[i][j] != -1 else inf]
min_op = lambda n: n[0] + n[3]

remain = n-1
sum_w = 0
while remain > 0:
    min_edge = min([min(E[i], key=min_op) for i in range(n)], key=min_op)
    w, i, j, _ = min_edge
    E[i][j][3] = E[j][i][3] = inf
    if not V[i].is_same(V[j]):
        V[i].union(V[j])
        sum_w += w
        remain -= 1
print(sum_w)

Python: n = int(input())
edgeList = []
rootList = [-1 for i in range(n)]

def getRoot(x):
    r = rootList[x]
    if r < 0:
        rootList[x] = x
    elif r != x:
        rootList[x] = getRoot(r)
    return rootList[x]
        
for i in range(n):
    a = list(map(int, input().split()))
    for j in range(i):
        if a[j] != -1:
            edgeList.append([a[j], getRoot(i), getRoot(j)])
sumLength = 0
edgeList.sort(key=lambda x: x[0])
for e in edgeList:
    x = e[1]
    y = e[2]
    if x != y:
        sumLength += e[0]
        rootList[x] = rootList[y] = min(x, y)
print(sumLength)