Go: package main

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

//util
var sc = bufio.NewScanner(os.Stdin)

func nextStr() string {
	sc.Scan()
	return sc.Text()
}

func nextInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}

func printList(list []int) {
	n := len(list)
	buf := bufio.NewWriter(os.Stdout)
	for _, v := range list[0 : n-1] {
		buf.Write([]byte(fmt.Sprintf("%d ", v)))
	}
	buf.Write([]byte(fmt.Sprintf("%d\n", list[n-1])))
	buf.Flush()
}

func max(a, b int) int {
	if a > b {
		return a
	} else {
		return b
	}
}

func min(a, b int) int {
	if a > b {
		return b
	} else {
		return a
	}
}

//solve
const (
	MAX   = 100
	INFTY = (1 << 21)
	WHITE = 0
	GRAY  = 1
	BLACK = 2
)

//V: グラフの頂点全体の集合
//T: MSTに属する頂点の集合
var (
	n     int
	M     [MAX][MAX]int //重みを記録する隣接行列
	color [MAX]int
	p     [MAX]int //MSTにおける頂点の親を記録
	d     [MAX]int //Tに属する頂点と、V−Tに属する頂点を繋ぐ辺の中で、重みが最小のものを記録
)

func prim() int {
	var u, minv int
	//初期化
	for i := 0; i < n; i++ {
		d[i] = INFTY
		p[i] = -1
		color[i] = WHITE
	}

	d[0] = 0

	for {
		//頂点uを決めていく
		//つまり、Tに属する頂点と、V−Tに属する頂点を繋ぐ辺の中で、重みが最小のものを決める
		minv = INFTY
		u = -1
		for i := 0; i < n; i++ {
			//未訪問かつ、辺の重みが最小となるuを選ぶ
			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] != INFTY {
				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() {
	sc.Split(bufio.ScanWords)
	n = nextInt()

	for i := 0; i < n; i++ {

		for j := 0; j < n; j++ {
			tmp := nextInt()
			if tmp == -1 {
				tmp = INFTY
			}
			M[i][j] = tmp
		}

	}

	fmt.Println(prim())

}

Python: def prim():
    distance[0] = 0
    parent[0] = -1

    while True:
        mincost = float('inf')
        for i in range(n):
            if color[i] != 'black' and distance[i] < mincost:
                mincost = distance[i]
                u = i
        if mincost == float('inf'):
            break

        color[u] = 'black'

        for v in range(n):
            if color[v] != 'black' and adjMat[u][v] != float('inf'):
                if adjMat[u][v] < distance[v]:
                    distance[v] = adjMat[u][v]
                    parent[v] = u
                    color[v] = 'gray'


n = int(input())
color = ['white'] * n
parent = [-1] * n
distance = [float('inf')] * n

adjMat = [[0] * n for _ in range(n)]
for i in range(n):
    adjRow = list(map(int, input().split()))
    for v in adjRow:
        if v == -1:
            adjMat[i][v] = float('inf')
        else:
            adjMat[i][v] = v

prim()

print(sum(distance))

Python: def solv(G):
  new_V = [0]
  new_E = []

  while len(new_V) < len(G):
    u, e = select_min(G, new_V)
    new_V.append(u)
    new_E.append(e)

  return sum(new_E)

def select_min(G, V):
  min_u = -1
  min_e = float('inf')
  for v in V:
    for u, e in enumerate(G[v]):
      if (e < 0) or (u in V): continue
      if e < min_e:
        min_u = u
        min_e = e
  return min_u, min_e

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

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

isVisited = [False] * n
d = [0] + [2001] * (n - 1)
p = [-1] * n

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

    if mincost == 2001:
        break

    isVisited[u] = True

    for v in range(n):
        if (not isVisited[v]) and (A[u][v] != -1): #uと繋がる頂点v
            if A[u][v] < d[v]:
                d[v] = A[u][v]
                p[v] = u

print(sum(d))

Python: import heapq
from collections import deque
from enum import Enum
import sys
import math
from _heapq import heappush, heappop

BIG_NUM = 2000000000
MOD = 1000000007
EPS = 0.000000001


class UnionFind:
    def __init__(self,arg_V):
        self.V = arg_V
        self.boss = [None]*arg_V
        self.height = [None]*arg_V

    def init(self):
        for i in range(self.V):
            self.boss[i] = i
            self.height[i] = 0

    def get_boss(self,index):
        if index == self.boss[index]:
            return index
        else:
            self.boss[index] = self.get_boss(self.boss[index])
            return self.boss[index]


    def is_same_group(self,a,b):
        return self.get_boss(a) == self.get_boss(b)

    def unite(self,x,y):
        boss_x = self.get_boss(x)
        boss_y = self.get_boss(y)

        if boss_x == boss_y:
            return

        if self.height[x] > self.height[y]:

            self.boss[boss_y] = boss_x

        elif self.height[x] < self.height[y]:

            self.boss[boss_x] = boss_y

        else:
            self.boss[boss_y] = boss_x
            self.height[x] += 1

class Edge:
    def __init__(self,arg_FROM,arg_TO,arg_WEIGHT):
        self.FROM = arg_FROM
        self.TO = arg_TO
        self.WEIGHT = arg_WEIGHT

    def __lt__(self,arg):
        return self.WEIGHT < arg.WEIGHT


V = int(input())

TABLE = []
for i in range(V):
    input_array = list(map(int,input().split()))
    for k in range(len(input_array)):
        if input_array[k] != -1:
            TABLE.append(Edge(i,k,input_array[k]))

UF = UnionFind(V)
UF.init()

TABLE.sort()

ans = 0

for i in range(len(TABLE)):
    if UF.is_same_group(TABLE[i].FROM, TABLE[i].TO) == False:
        UF.unite(TABLE[i].FROM, TABLE[i].TO)
        ans += TABLE[i].WEIGHT

print("%d"%(ans))

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:
            for i, a in enumerate(M[j-1], 1):
                if i in h:
                    continue
                if 0 < a < minimum:
                    index = i
                    minimum = a
        h.add(index)
        g.remove(index)
        gravity += minimum

    print(gravity)


main()

Python: n = int(input())
edge = []
for i in range(n):
    a = list(map(int, input().split()))
    for j in range(i + 1, n):
        if a[j] != -1:
            edge.append((a[j], i, j))
edge.sort()
ans = 0

tree = [i for i in range(n)]
def root(x):
    pre = []
    while x != tree[x]:
        pre.append(x)
        x = tree[x]
    for node in pre:
        tree[node] = x
    return x
def unite(x, y):
    X, Y = root(x), root(y)
    if X != Y:
        tree[X] = Y

for cost, x, y in edge:
    X, Y = root(x), root(y)
    if X != Y:
        ans += cost
        tree[X] = Y
print(ans)

Python: import sys
input = sys.stdin.readline
from operator import itemgetter
sys.setrecursionlimit(10000000)
INF = 10**30
M = []

def prim(G, root, n):
    BLACK = 1<<10
    WHITE = 1<<20
    nodes = [WHITE] * n
    d = [INF] * n
    d[root] = 0
    p = [0] * n
    p[root] = -1
    while True:
        mincost = INF

        # 探索
        for i in range(n):
            if d[i] < mincost and nodes[i] == WHITE:
                mincost = d[i]
                next = i
        if mincost == INF:
            break
        # 移動
        nodes[next] = BLACK

        # 伝播
        for i in range(n):
            if nodes[i] == WHITE and G[next][i] != INF:
                if G[next][i] < d[i]:
                    d[i] = G[next][i]
                    p[i] = next
    return d

def main():
    global M
    n = int(input().strip())
    M = [[0] * n for _ in range(n)]
    for i in range(n):
        M[i] = list(map(lambda x: INF if x == -1 else x, map(int, input().strip().split())))
    d = prim(M, 0, n)
    print(sum(d))

if __name__ == '__main__':
    main()