Go: package main

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

const (
	MAX_N      = 200
	MAX_WEIGHT = 2000
)

type Edge struct {
	start  int
	end    int
	weight int
}

type ShortestInfo struct {
	edges    []Edge
	shortest int
}

func main() {
	sc := bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)

	n, err := nextInt(sc)
	if err != nil {
		panic(err)
	}

	shortestList := make([]ShortestInfo, n)
	for i := 1; i < n; i++ {
		shortestList[i] = ShortestInfo{edges: []Edge{}, shortest: MAX_N*MAX_WEIGHT + 1}
	}

	adjacentMatrix := make([][]int, n)
	for i := 0; i < n; i++ {
		adjacentMatrix[i] = make([]int, n)
		for j := 0; j < n; j++ {
			v, err := nextInt(sc)
			if err != nil {
				panic(err)
			}
			adjacentMatrix[i][j] = v
		}
	}

	mst([]int{1}, shortestList, adjacentMatrix)
	fmt.Println(shortestList)
	fmt.Println(calculateMinWeight(shortestList))
}

func calculateMinWeight(shortestList []ShortestInfo) int {
	visitedList := make([]bool, len(shortestList))
	visitedList[0] = true
	sumWeight := 0
	for !visitedAll(visitedList) {
		shortestInfo := shortestList[0]
		shortestList = shortestList[1:]
		edges := shortestInfo.edges
		for _, edge := range edges {
			if !visitedList[edge.end-1] {
				visitedList[edge.end-1] = true
				sumWeight += edge.weight
			}
		}
	}
	return sumWeight
}

func visitedAll(visitedList []bool) bool {
	for _, v := range visitedList {
		if !v {
			return false
		}
	}
	return true
}

func mst(nodeStack []int, shortestList []ShortestInfo, adjacentMatrix [][]int) {
	for len(nodeStack) > 0 {
		currentNode := nodeStack[0]
		nodeStack = nodeStack[1:]
		currentShortest := getShortest(currentNode, shortestList)
		adjacents := findAdjacents(currentNode, adjacentMatrix)
		for i := 0; i < len(adjacents); i++ {
			adj := adjacents[i]
			s := getShortest(adj.end, shortestList)
			if currentShortest.shortest+adj.weight < s.shortest || (currentShortest.shortest+adj.weight == s.shortest && len(currentShortest.edges)+1 > len(s.edges)) {
				setShortest(adj.end, adj, currentShortest, shortestList)
				nodeStack = append(nodeStack, adj.end)
			}
		}
	}
}

func getShortest(node int, shortestList []ShortestInfo) ShortestInfo {
	return shortestList[node-1]
}

func setShortest(node int, edge Edge, currentShortest ShortestInfo, shortestList []ShortestInfo) {
	newEdges := make([]Edge, len(currentShortest.edges)+1)
	for i := 0; i < len(newEdges)-1; i++ {
		newEdges[i] = currentShortest.edges[i]
	}
	newEdges[len(newEdges)-1] = edge
	shortestInfo := ShortestInfo{edges: newEdges, shortest: currentShortest.shortest + edge.weight}
	shortestList[node-1] = shortestInfo
}

func findAdjacents(currentNode int, adjacentMatrix [][]int) []Edge {
	adjacents := adjacentMatrix[currentNode-1]
	edges := []Edge{}
	for i, v := range adjacents {
		if v > 0 {
			edges = append(edges, Edge{start: currentNode, end: i + 1, weight: v})
		}
	}
	return edges
}

func nextInt(sc *bufio.Scanner) (int, error) {
	sc.Scan()
	return strconv.Atoi(sc.Text())
}

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)