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: #!/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}
    gravity = 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)
        gravity += minimum

    print(gravity)


main()

Python: import sys
import heapq

def main():
    n = int(input())
    next = []
    for _ in range(n):
        l = list(map(int, input().split()))
        next.append([(c, i) for i, c in enumerate(l) if c != -1])
    visited = [0] * n
    connection = 0
    q = [(0, 0)]    # (cost, v)
    heapq.heapify(q)
    ans = 0
    while len(q):
        cost, v = heapq.heappop(q)
        if visited[v]:
            continue

        # そのノードと繋げる
        visited[v] = 1
        connection += 1
        ans += cost
        
        # 新たに繋げたノードから行けるところをエンキュー
        for i in next[v]:
            heapq.heappush(q, i)
        
        # 全部のノードが繋がったら終了
        if connection == n:
            break
    print(ans)
    return

if __name__ == '__main__':
    main()

Python: N = 100

n = int(input())
adj = [[0 for i in range(n)] for j in range(n)]

for i in range(n):
    tmp = list(map(int, input().split()))
    u = tmp[0]
    u = u -1
    k = tmp[1]
    v = tmp[2:]
    for j in range(k):
        adj[u][v[j]-1] = 1
        
for i in range(n):
    for j in range(n):
        print(adj[i][j], end=" ")
    print()

Python: N = int(input())
L = []  # input


def prim():
    # 頂点を適当に選ぶ
    s = None
    for i in range(N):
        for j in range(N):
            if L[i][j] != -1:
                s = i
                break
        if s is not None:
            break
    p = {s}
    T = []
    k = 0
    while k < N - 1:
        # 最終のP内で一番短いやつを加える
        len = float("inf")
        lenside = []
        for sg in p:
            for i in range(N):
                isT = False
                for t in T:
                    if (t[0] == sg and t[1] == i) or (t[0] == i and t[1] == sg):
                        # print("ignore")
                        isT = True
                        continue
                if isT is False and i not in p and L[sg][i] != -1 and L[sg][i] < len:
                    len = L[sg][i]
                    lenside = [sg, i]

        p.add(lenside[0])
        p.add(lenside[1])
        T.append(lenside)
        k = k + 1
        #print(p,T,k)
    cnt = 0
    for t in T:
        cnt += L[t[0]][t[1]]
    print(cnt)


for i in range(N):
    L.append(list(map(int, input().split())))
prim()

Python: import sys, collections
input = lambda: sys.stdin.readline().rstrip() 
sys.setrecursionlimit(10**7)
INF = 10**10
def I(): return int(input())
def F(): return float(input())
def SS(): return input()
def LI(): return [int(x) for x in input().split()]
def LI_(): return [int(x)-1 for x in input().split()]
def LF(): return [float(x) for x in input().split()]
def LSS(): return input().split()

class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n

    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]

    def unite(self, x, y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return

        if self.parents[x] > self.parents[y]:
            x, y = y, x

        self.parents[x] += self.parents[y]
        self.parents[y] = x

    def same(self, x, y):
        return self.find(x) == self.find(y)

def kruskal(es, V):
    es.sort(key=lambda x:x[2])
    uf = UnionFind(V)
    res = 0
    for e in es:
        if not uf.same(e[0], e[1]):
            uf.unite(e[0], e[1])
            res += e[2]
    return res

def resolve():
    n = I()
    es = []
    for i in range(n):
        a = LI()
        for j in range(n):
            if a[j]!=-1:
                es.append((i, j, a[j]))

    ans = kruskal(es, n)
    print(ans)

if __name__ == '__main__':
    resolve()

Python: import heapq


def prim(adj):
    INF = 3000
    n = len(adj)
    state, d, p = [False] * n, [INF] * n, [-1] * n
    d[0] = 0
    pq = [(d[0], 0)]
    while pq:
        f, u = heapq.heappop(pq)
        state[u] = True
        if d[u] < f:
            continue
        for v, c in adj[u]:
            if state[v]:
                continue
            if c < d[v]:
                d[v] = c
                p[v] = u
                heapq.heappush(pq, (d[v], v))
    return d


def adj_matrix_to_list(matrix):
    n = len(matrix)
    li = [[] for _ in range(n)]
    for u in range(n):
        for v in range(n):
            if matrix[u][v] != -1:
                li[u].append((v, matrix[u][v]))
    return li


def main():
    n = int(input())
    m = [list(map(int, input().split())) for _ in range(n)]
    adj = adj_matrix_to_list(m)
    print(sum(prim(adj)))


if __name__ == '__main__':
    main()