Go: package main

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

func getScanner(fp *os.File) *bufio.Scanner {
	scanner := bufio.NewScanner(fp)
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, 500001), 500000)
	return scanner
}

func getNextString(scanner *bufio.Scanner) string {
	scanner.Scan()
	return scanner.Text()
}

func getNextInt(scanner *bufio.Scanner) int {
	i, _ := strconv.Atoi(getNextString(scanner))
	return i
}

func main() {
	fp := os.Stdin
	if len(os.Args) > 1 {
		fp, _ = os.Open(os.Args[1])
	}

	scanner := getScanner(fp)
	writer := bufio.NewWriter(os.Stdout)

	n := getNextInt(scanner)

	g := make([][]int, n)
	ans := make([][]int, n)

	inf := 1 << 30
	for i := 0; i < n; i++ {
		g[i] = make([]int, n)
		ans[i] = make([]int, n)
		for ii := 0; ii < n; ii++ {
			g[i][ii] = getNextInt(scanner)
			if g[i][ii] == -1 {
				g[i][ii] = inf
			}
			ans[i][ii] = -1
		}
	}

	im := make(IntMap, 1)

	im.increment(1)

	for len(im) < n {
		min := inf
		u := -1
		v := -1
		for i := range im {
			for ii := 0; ii < n; ii++ {
				if im.get(ii) != 0 {
					continue
				}
				if min > g[i][ii] {
					min = g[i][ii]
					u = i
					v = ii
				}
			}
		}
		im.increment(v)
		ans[u][v] = min
		ans[v][u] = min
	}

	sum := 0
	for i := 0; i < n-1; i++ {
		for ii := i + 1; ii < n; ii++ {
			if ans[i][ii] != -1 {
				sum += ans[i][ii]
			}
		}
	}

	fmt.Fprintln(writer, sum)
	writer.Flush()
}

// IntMap ...
type IntMap map[int]int

func (m IntMap) get(key int) int {
	if _, ok := m[key]; ok {
		return m[key]
	}
	return 0
}
func (m IntMap) increment(key int) {
	if _, ok := m[key]; ok == false {
		m[key] = 0
	}
	m[key]++
}

Python: # -*- coding: utf-8 -*-
"""
Created on Sat Jul 14 19:11:44 2018

@author: maezawa
"""

n = int(input())
m = []
for i in range(n):
    mi = list(map(int, input().split()))
    m.append(mi)

#print(*m, sep='\n')

color = [0]*n
d = [10**9]*n
p = [0]*n
p[0] = -1

def prim():
    while True:
        mincost = 10**9
        for i in range(n):
            if color[i] != 2 and d[i] < mincost:
                mincost = d[i]
                u = i
        if mincost == 10**9:
            break

        color[u] = 2

        for v in range(n):
            if color[v] != 2 and m[u][v] != -1:
                if m[u][v] < d[v]:
                    d[v] = m[u][v]
                    p[v] = u
                    color[v] = 1
    sumw = 0
    for i in range(n):
        if p[i] != -1:
            sumw += m[i][p[i]]
    return sumw

print(prim())

Python: def prim(n, M):
    color = [0 for _ in range(n)]
    d = [5000 for _ in range(n)]
    p = [-1 for _ in range(n)]

    d[0] = 0

    while True:
        mincost = 100000
        u = -1

        for i, dt in enumerate(d):
            if dt < mincost and color[i] != 1:
                mincost = dt
                u = i

        # ??´??°???????????£?????´???
        if mincost == 100000:
            break

        color[u] = 1

        for v in range(n):
            # ????????????, ?????????????¨???????????????¨??????
            if M[u][v] != 5000 and color[v] != 1:
                if M[u][v] < d[v]:
                    d[v] = M[u][v]
                    p[v] = u

    all_sum = 0

    for i, p_dt in enumerate(p):
        if p_dt != -1:
            all_sum += M[i][p_dt]

    return all_sum


def main():
    n = int(input())
    M = []

    for _ in range(n):
        dt = input().split(' ')
        M.append([5000 if int(d) == -1 else int(d) for d in dt])

    answer = prim(n, M)

    print(answer)

if __name__ == '__main__':
    main()

Python: n = int(input())
g = [[] for i in range(n)]
for i in range(n):
    *v, = map(int, input().split())
    for j in range(n):
        if v[j] < 0:
            v[j] = 10000
    g[i] = v

ans = 0
t = [0]
v = [i for i in range(1, n)]
while len(t) < n:
    u = [2000, 0, 0]
    for tv in t:
        for vv in v:
            if g[tv][vv] < u[0]:
                u = [g[tv][vv], tv, vv]
    ans += u[0]
    t.append(u[2])
    v.remove(u[2])
print(ans)

Python: n = int(input())
INFTY = 10**5
WHITE = 0
GRAY = 1
BLACK = 2

A = [[ int(row) if row != "-1" else INFTY for row in input().split()] for i in range(n)]

def prim(A, st):
    colors = [WHITE] * n
    colors[st] = BLACK
    T = [st]
    total_weights = 0
    
    while len(T) < n:
    
        current_min = INFTY
        next_add = st
        for node_inT in T:
            for v in range(n):
                if colors[v] == WHITE and A[node_inT][v] < current_min:
                    current_min = A[node_inT][v]
                    next_add = v

        total_weights += current_min
        T.append(next_add)
        colors[next_add] = BLACK
    
    return total_weights

MST = [0] * n
for i in range(n):
    MST[i] = prim(A, i)

print(min(MST))

Python: from __future__ import division, print_function
from sys import stdin, maxint
 
 
def main():
    num = int(stdin.readline())
 
    y = []
    for _ in xrange(num):
        it = iter(int(s) for s in stdin.readline().split()[1:])
        y.append([(next(it), next(it)) for _ in xrange(next(it))])
    weight = [maxint] * num
    weight[0] = 0
    t = set(xrange(1, num))
    index = 0
 
    while t:
        for v, cost in y[index]:
            if v not in t:
                continue
            weight[v] = min(weight[v], cost + weight[index])

        index = min(t, key=lambda i: weight[i])
        t.remove(index)

    for i, d in enumerate(weight):
        print(i, d)
 
 
main()

Python: # coding: utf-8

n = int(input())
ew = [None] * n
for i in range(n):
    ew[i] = list(map(int, input().split()))

elist = []
for i in range(n):
    for j in range(i+1, n):
        if ew[i][j] > -1:
            elist.append((ew[i][j], i, j))


class UnionFind(object):
    def __init__(self, n):
        self.parent = [i for i in range(n)]

    def find_root(self, i):
        if self.parent[i] != i:
            p = self.parent[i]
            self.parent[i] = self.find_root(p)
        return self.parent[i]

    def same_group(self, i, j):
        return self.find_root(i) == self.find_root(j)

    def union(self, i, j):
        i = self.find_root(i)
        j = self.find_root(j)
        if i != j:
            self.parent[j] = i


uf = UnionFind(n)
esum = 0
for edge in sorted(elist):
    if not uf.same_group(edge[1], edge[2]):
        uf.union(edge[1], edge[2])
        esum += edge[0]

print(esum)

Python: # -*- coding: utf-8 -*-
"""
Created on Sat Apr  6 18:01:32 2019

@author: Yamazaki Kenichi
"""

n = int(input())
A = [list(map(int,input().split())) for i in range(n)]
INFTY = 10**6
T = [-1 for i in range(n)]
d = [INFTY for i in range(n)]
p = [0 for i in range(n)]
d[0], p[0] = 0, -1
for j in range(n):
    mincost = 10**6
    for i in range(n):
        if T[i] != 1 and d[i] < mincost:
            mincost = d[i]
            u = i
    T[u] = 1
    for v in range(n):
        if T[v] != 1 and A[u][v] != -1:
            if A[u][v] < d[v]:
                d[v] = A[u][v]
                p[v] = u
                T[v] = 0
print(sum(d))

Python: n = int(input())
edgeArray = [list(map(int, input().split())) for i in range(n)]
edgeList = []
rootList = [-1 for i in range(n)]
sumLength = 0

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):
    for j in range(i):
        if edgeArray[i][j] != -1:
            edgeList.append([edgeArray[i][j], i, j])
edgeList.sort(key=lambda x: x[0])
for e in edgeList:
    x = getRoot(e[1])
    y = getRoot(e[2])
    if x != y:
        sumLength += e[0]
        rootList[x] = rootList[y] = min(x, y)
print(sumLength)