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: # -*- coding: utf-8 -*-
def prim(edges, *, start=0, adj_matrix=False, default_value=float('inf')):
    '''
    Returns the Minimum Spanning Tree(MST) of a given graph

    # sample input when given not as adjacency list (generally works faster)
    edges = [[(1, 2), (2, 5), (3, 4)],         # node 0
             [(0, 2), (3, 3), (4, 6)],         # node 1
             [(0, 5), (3, 2), (5, 6)],         # node 2
             [(0, 4), (1, 3), (2, 2), (4, 2)], # node 3
             [(1, 6), (3, 2), (5, 4)],         # node 4
             [(2, 6), (4, 4)]]                 # node 5

    # sample input when given as adjacency matrix
    edges = [[0, 2, 5, 4, inf, inf],           # node 0
             [2, 0, inf, 3, 6, inf],           # node 1
             [5, inf, 0, 2, inf, 6],           # node 2
             [4, 3, 2, 0, 2, inf],             # node 3
             [inf, 6, inf, 2, 0, 4],           # node 4
             [inf, inf, 6, inf, 4, 0]]         # node 5
    '''

    n = len(edges)
    mst = []
    cost = 0
    T = [start]

    while True:
        tmp_edges = [(cost, (u, v)) for u in T for v, cost in enumerate(edges[u]) if cost != default_value and v not in T] if adj_matrix else\
                    [(cost, (u, v)) for u in T for v, cost in edges[u] if v not in T]

        if tmp_edges:
            min_cost, min_edge = min(tmp_edges)
            mst.append(min_edge)
            cost += min_cost
            T.append(min_edge[1])

        else:
            if len(mst) != n - 1:
                raise NoSpanningError(
                    'There is no spanning tree in this graph (search started from node{})'.
                    format(start))

            else:
                return mst, cost


class NoSpanningError(Exception):
    pass


if __name__ == '__main__':
    '''
    an example of using this function
    AIZU ONLINE JUDGE - ALDS_1_12_A
    '''

    n = int(input())
    edges = [[int(cost) if int(cost) != -1 else float('inf') for cost in input().split()] for i in range(n)]

    print(prim(edges, adj_matrix=True)[1])

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

    while True:
        #MSTに追加する頂点を決定
        mincost = INF
        u = -1
        for i in range(n):
            if color[i] != black and mindist[i] < mincost:
                mincost = mindist[i]
                u = i
        if u == -1: break
        color[u] = black
        # MSTに含まれていないMSTとつながる隣接頂点の最小コストを探索
        for v in range(n):
            if color[v] == black: continue
            if M[u][v] == INF: continue
            if M[u][v] >= mindist[v]: continue
            mindist[v] = M[u][v] 
            parent[v] = u
            color[v] = gray
        
    sumcost = 0
    for i in range(n):
        if parent[i] == -1: continue
        sumcost += M[i][parent[i]]

    return sumcost

if __name__ == "__main__":
    n = int(input())
    INF = float("inf")
    M = [list(map(lambda x: INF if x == "-1" else int(x), input().split())) for _ in range(n)]
    white = 0; gray = 1; black =2
    color = [white]*n #各頂点の訪問状態 （white:未訪問 gray:暫定 black:確定）
    mindist = [INF]*n # 各頂点のMSTとつながる辺の最小コスト
    parent = [-1]*n #各頂点の親

    print(prim())

Python: #!/usr/bin/env python3
# n,m = map(int,sys.stdin.readline().split())
# a = tuple(map(int,sys.stdin.readline().split())) # single line with multi param
# a = tuple(sys.stdin.readline() for _ in range(n)) # multi line with single param
# a = tuple(tuple(map(int,sys.stdin.readline().rstrip().split()) for _ in range(N))) # multi line with multi param
# s = sys.stdin.readline().rstrip()
# n = int(sys.stdin.readline())
# INF = float("inf")
import sys,collections
N = int(sys.stdin.readline())
G = tuple(tuple(map(int,sys.stdin.readline().rstrip().split()) for _ in range(N))) # multi line with multi param

INF = float("inf")
W = [INF]*N
A = set(range(N))
T = set()

def add(e):
  T.add(e)
  for i,w in enumerate(G[e]):
    if not i in T and w != -1:
      W[i] = min(W[i],w)
  if not A-T:#W[-1] = -INF
    return -1
  m = min((W[i],i) for i in A-T)
  #print(W,T,m)
  return m[1]

n = add(0)
W[0] = 0
while len(T) < len(G):
  n = add(n)
print(sum(W))

Python: import itertools

n = int(input())
A = []
for i in range(n):
    line = input()
    A.append([int(x) for x in line.split()])


V = set(range(n))
Vnew = {0}  # ??¨???????°???¨?????????
weights = []

while V != Vnew:
    T = V - Vnew
    minw = float('inf')
    for u, v in itertools.product(Vnew, T):
        w = A[u][v]
        if w != -1 and minw > w:
            e = (u, v)
            minw = w
    Vnew.add(e[1])
    weights.append(minw)

print(sum(weights))

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:] -1
    for j in range(k):
        adj[u][v[j]] = 1
        
for i in range(n):
        print(" ".join(list(map(str, adj[i]))))

Python: def root(x):
    path_to_root = []
    while x != P[x]:
        path_to_root.append(x)
        x = P[x]
    for node in path_to_root:
        P[node]=x
    return x

def unite(x,y):
    P[root(x)] = root(y)

def is_same_set(x,y):
    return root(x) == root(y)

n = int(input())
P = [i for i in range(n)]
length=[]
points=[]
for i in range(n):
    length.append(list(map(int,input().split())))
for i in range(n):
    for j in range(i,n):
        if length[i][j] != -1:
            points.append((i,j,length[i][j]))
	
points.sort(key=lambda x:x[2])

totalweight = 0
for p in points:
    i,j,w = p
    if not is_same_set(i,j):
       totalweight += w
       unite(i,j)

print(totalweight)