Go: package main

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

const (
	white int = iota
	gray
	black
)
const INFTY int = 2001

var G [][]int
var color []int
var d []int
var p []int
var N int

func prim() int {
	u := 0
	d[u] = 0
	for {
		minCost := INFTY
		for i:=0; i<N; i++ {
			if color[i] != black && d[i] < minCost {
				minCost = d[i]
				u = i
			}
		}

		if minCost == INFTY {
			break
		}

		color[u] = black

		for v:=0; v<N; v++ {
			if color[v] != black && G[u][v] != -1 {
				if G[u][v] < d[v] {
					d[v] = G[u][v]
					p[v] = u
					color[v] = gray
				}
			}
		}
	}
	// sum
	sum := 0
	for i:=0; i<N; i++ {
		if p[i] != -1 {
			sum += G[i][p[i]]
		}
	}
	return sum
}




func initVariable(N int) {
	G = make([][]int, N)
	for i:=0; i<N; i++ {
		G[i] = make([]int, N)
	}
	color = make([]int, N)
	d = make([]int, N)
	p = make([]int, N)
	for i:=0; i<N; i++ {
		d[i] = INFTY
		p[i] = -1
	}
}

func nextInt(scanner *bufio.Scanner) int {
	scanner.Scan()
	num, _ := strconv.Atoi(scanner.Text())
	return num
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	N = nextInt(scanner)
	initVariable(N)
	for i:=0; i<N; i++ {
		for j:=0; j<N; j++ {
			G[i][j] = nextInt(scanner)
		}
	}
	fmt.Printf("%d\n", prim())
}

Python: import heapq

n = int(input())
#A = [[int(i) for i in input().split()] for i in range(n)]
h = []
DP = {}
heapq.heappush(h,(0,0))
c = 0
while(len(DP)<n):
    tmp = heapq.heappop(h)
    if tmp[1] in DP:
        continue
    c += tmp[0]
    DP[tmp[1]] = 1
    for i,j in enumerate(A[tmp[1]]):
        if j > 0 and not i in DP:
            heapq.heappush(h,(j,i))
print(c)

Python: n=int(input())
M=[list(map(int,input().split()))for _ in[0]*n]
d=[0]+[1e4]*~-n
p=[-1]*n
b=[1]*n
while 1:
 m,u=1e4,-1
 for i in range(n):
  if m>d[i]and b[i]:m,u=d[i],i
 if u<0:break
 b[u]=0
 for v in range(n):
  if b[v]and 1+M[u][v]and d[v]>M[u][v]:
   d[v],p[v]=M[u][v],u
print(sum(M[i][p[i]]for i in range(n)if p[i]+1))

Python: n = int(input())
edgeList = []
for i in range(n):
    a = list(map(int, input().split()))
    for j in range(i):
        if a[j] != -1:
            edgeList.append([a[j], i, j])
rootList = [-1]*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]
        

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)

Python: INF = 9999


def prim(G):
    n = len(G)
    color = ['White' for _ in range(n)]
    d = [INF for _ in range(n)]
    p = [-1 for _ in range(n)]
    d[0] = 0

    while True:
        mincost = INF
        u = -1
        for i in range(n):
            if color[i] != 'Black' and d[i] < mincost:
                mincost = d[i]
                u = i

        if u == -1:
            break

        color[u] = 'Black'

        for v in range(n):
            if color[v] != 'Black' and G[u][v] != INF:
                if G[u][v] < d[v]:
                    d[v] = G[u][v]
                    p[v] = u
                    color[u] = 'Gray'

        sum = 0
        for i in range(n):
            if p[i] != -1:
               sum += G[i][p[i]]
        return sum


if __name__ == '__main__':
    n = int(input())
    GL = [list(map(int, input().split())) for _ in range(n)]
    for i in range(n):
        for j in range(n):
            if GL[i][j] == -1:
                GL[i][j] = INF
    print(prim(GL))

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))