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: import heapq

n = int(input())
edges = [set((w, j) for j, w in enumerate(map(int, input().split())) if w > -1) for _ in range(n)]

visited = [False] * n
visited[0] = True
queue = list(edges[0])
heapq.heapify(queue)
total_cost, remains = 0, n - 1
while True:
    cost, vertex = heapq.heappop(queue)
    if visited[vertex]:
        continue
    visited[vertex] = True
    total_cost += cost
    remains -= 1
    if not remains:
        break
    for t in edges[vertex]:
        if not visited[t[1]]:
            heapq.heappush(queue, t)

print(total_cost)

Python: n = int(input())
m = [[-1 for i in range(n)] for j in range(n)] #お隣さんへのコストを保存（この中から最小を探す）

v = set()
v.add(0)

for i in range(n): #隣接の辺のコストを入力
  nums = list(map(int, input().split()))
  for j in range(n):
    m[i][j] = nums[j]


def prim_mst(n):
  isVisited = [False] * n
  d = [0] + [2001] * (n-1)      #TとV-Tのを繋ぐ最小辺の重みを格納する

  while  True:
    mincost = 2001
    for i in range(n):
      if not (isVisited[i]) and d[i] < mincost:
        mincost = d[i]
        u = i
    isVisited[u] = True


    if mincost == 2001:        #mincostが2001になったら繰り返し作業終了
      break

    for v in range (n):
      if (not isVisited[v]) and (m[u][v] != -1):
        if m[u][v] < d[v]:
          d[v] = m[u][v]
  print(sum(d))

prim_mst(n)

Python: import heapq

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

q = []

visited = [False]*n

adjs = []
sum_cost = 0
node = 0
visited[node] = True
cnt = 1

while 1:
    for i in range(n):
        if M[node][i] != -1 and visited[i] == False:
            heapq.heappush(q, (M[node][i], i))
    while 1:
        mincost,node = heapq.heappop(q)
        if visited[node] == False:
            break
    sum_cost += mincost
    visited[node] = True
    cnt += 1
    if cnt == n:
        break


print(sum_cost)

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):
        print(" ".join(list(map(str, adj[i]))))

Python: import sys

n = int(sys.stdin.readline())
g = [list(map(int, sys.stdin.readline().split())) for _ in range(n)]

V = set(range(n))
U = set()
E = []

U.add(V.pop())

while len(U)<n:
    minw = 1e10
    mine = []
    for u in U:
        for v in V:
            if g[u][v]>=0 and minw>g[u][v]:
                minw = g[u][v]
                mine = [u, v]
    E.append(mine)
    U.add(mine[1])
    V.remove(mine[1])

vv=0
for u, v in E:
    vv += g[u][v]
print(vv)

Python: def prim(n, cost):
    mincost = [float("inf")]*n
    used = [False] * n
    mincost[0] = 0
    res = 0
    cnt = 1
    while True:
        u = -1
        for i in range(n):
            if (not used[i]) and (u == -1 or mincost[i] < mincost[u]):
                u = i
        if u == -1:
            break
        used[u] = True
        res += mincost[u]
        for v in range(n):
            if cost[u][v] != -1:
                mincost[v] = min(mincost[v], cost[u][v])
    return res


def main():
    n = int(input())
    g = []
    for _ in range(n):
        g.append(list(map(int, input().split())))
    print(prim(n, g))



if __name__ == '__main__':
    main()

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

for i in range(n):
  for index, j in enumerate(list(map(int, input().split()))):
    edges[i][index] = j

inf = 9999999999999999
distances = [inf] * n
colors = ["white"] * n

def mst(u):
  distances[u] = 0
  colors[u] = "gray"

  while True:
    mincost = inf
    for i in range(n):
      if colors[i] != "black" and distances[i] < mincost:
        mincost = distances[i]
        u = i

    if mincost == inf:
      break

    colors[u] = "black"

    for index, weight in enumerate(edges[u]):
      if weight != -1 and colors[index] != "black" and distances[index] > weight:
        distances[index] = weight
        colors[index] = "gray"

mst(0)
print(sum(distances))

Python: MAX = 2001


def prim(tree: [int], adjacent_list: [[int]]):
    cost = 0
    next = 0
    for l in adjacent_list:
        l[next] = MAX
    while True:
        tree.append(next)
        min_list = list()
        for t in tree:
            min_list.append(min([(v, i) for i, v in enumerate(adjacent_list[t])]))
        min_cost, i = min(min_list)
        if min_cost == MAX:
            return cost
        cost += min_cost
        for l in adjacent_list:
            l[i] = MAX
        print(adjacent_list)
        next = i


if __name__ == '__main__':
    N = int(input())
    adjacent_list = [[int(e) if int(e) != -1 else MAX for e in input().rstrip().split()] for _ in range(N)]
    test_list = []
    print(prim(test_list, adjacent_list))

Python: from __future__ import division, print_function
from sys import stdin, maxint
 
 
def main():
    x = int(stdin.readline())
 
    y = []
    for _ in xrange(x):
        y.append([int(s) for s in stdin.readline().split()])
 
    g = set(xrange(1, x+1))
    index = g.pop()
    h = {index}
    leng = 0
 
    while g:
        minimum = maxint

        for j in h:
            mj = y[j-1]
            for i in g:
                if 0 <= mj[i-1] < minimum:
                    index = i
                    minimum = mj[i-1]

        h.add(index)
        g.remove(index)
        leng += minimum
 
    print(leng)
 
 
main()