Go: package main

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

// I/O
type Scanner struct {
	sc *bufio.Scanner
}

func NewScanner() *Scanner {
	sc := bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)
	sc.Buffer(make([]byte, 1024), int(1e+9))
	return &Scanner{sc}
}

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

func (s *Scanner) nextInt() int {
	i, e := strconv.Atoi(s.nextStr())
	if e != nil {
		panic(e)
	}
	return i
}

func (s *Scanner) nextFloat() float64 {
	f, e := strconv.ParseFloat(s.nextStr(), 64)
	if e != nil {
		panic(e)
	}
	return f
}

func (s *Scanner) nextRuneSlice() []rune {
	return []rune(s.nextStr())
}

func (s *Scanner) nextIntSlice(n int) []int {
	res := make([]int, n)
	for i := 0; i < n; i++ {
		res[i] = s.nextInt()
	}
	return res
}

func (s *Scanner) nextFloatSlice(n int) []float64 {
	res := make([]float64, n)
	for i := 0; i < n; i++ {
		res[i] = s.nextFloat()
	}
	return res
}

// Arithmetic
func max(nums ...int) int {
	m := nums[0]
	for _, i := range nums {
		if m < i {
			m = i
		}
	}
	return m
}

func min(nums ...int) int {
	m := nums[0]
	for _, i := range nums {
		if m > i {
			m = i
		}
	}
	return m
}

func abs(x int) int {
	if x > 0 {
		return x
	}
	return -x
}

func pow(x, y int) int {
	res := 1
	for i := 0; i < y; i++ {
		res *= x
	}
	return res
}

func ceil(a, b int) int {
	if a%b == 0 {
		return a / b
	} else {
		return a/b + 1
	}
}

// Sort
type RuneSlice []rune

func (a RuneSlice) Len() int           { return len(a) }
func (a RuneSlice) Less(i, j int) bool { return a[i] < a[j] }
func (a RuneSlice) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }

const INF = 1 << 60

// Main
func main() {
	sc := NewScanner()
	wtr := bufio.NewWriter(os.Stdout)
	N := sc.nextInt()
	G := make([][]int, N)
	for i := 0; i < N; i++ {
		G[i] = make([]int, N)
		for j := 0; j < N; j++ {
			G[i][j] = sc.nextInt()
		}
	}
	d := make([]int, N)
	for i := 0; i < N; i++ {
		d[i] = INF
	}
	seen := make([]bool, N)
	d[0] = 0
	ans := 0
	for {
		cur := 0
		minCost := INF
		for i := 0; i < N; i++ {
			if !seen[i] && d[i] < minCost {
				minCost = d[i]
				cur = i
			}
		}
		if minCost == INF {
			break
		}
		seen[cur] = true
		ans += d[cur]
		for i := 0; i < N; i++ {
			cost := G[cur][i]
			if cost != -1 && cost < d[i] {
				d[i] = cost
			}
		}
	}

	fmt.Fprintln(wtr, ans)
	wtr.Flush()
}

Python: from sys import stdin
input = stdin.readline

INFTY = 2**21
WHITE = 0
GRAY = 1
BLACK = 2

n = int(input())

M = [[0]*n for _ in range(n)]

for i in range(n):
    ee = map(int, input().split())
    for j, e in enumerate(ee): # 先に1行分読み込んでから、eにわける
        if e == -1:
            M[i][j] = INFTY
        else:
            M[i][j] = e


def prim():
    d = [INFTY]*n
    p = [-1]*n
    color = [WHITE]*n

    d[0] = 0

    while True:
        minv = INFTY
        u = -1
        for i in range(n):
            if (minv > d[i]) and (color[i] != BLACK):
                u = i
                minv = d[i]

        if u == -1:
            break
        color[u] = BLACK
        for v in range(n):
            if (color[v] != BLACK) and (M[u][v] != INFTY):
                if d[v] > M[u][v]:
                    d[v] = M[u][v]
                    p[v] = u
                    color[v] = GRAY

    _sum = 0 # pythonは標準でsum関数があるので一応sumは使わないでおく
    for i in range(n):
        if p[i] != -1:
            _sum += M[i][p[i]]

    return _sum

print(prim())

Python: import heapq

n = int(input())
edges = [set((w, j) for j, w in enumerate(map(int, input().split())) if w > -1) for _ in range(n)]

visited = [False] * n
visited[0] = True
queue = list(edges[0])
heapq.heapify(queue)
total_cost, remains = 0, n - 1
while True:
    cost, vertex = heapq.heappop(queue)
    if visited[vertex]:
        continue
    visited[vertex] = True
    total_cost += cost
    remains -= 1
    if not remains:
        break
    queue.extend(edges[vertex])
    heapq.heapify(queue)

print(total_cost)

Python: def prim(n):
    inf=float("inf")
    D=[inf for i in range(n)]
    P=[0 for i in range(n)]
    M=[[inf for i in range(n)] for j in range(n)]
    color=["white" for i in range(n)]

    P[0]=-1
    D[0]=0

    for i in range(n):
        for j,num in enumerate(list(map(int,input().split()))):
            if num!=-1:
                M[i][j]=num

    while 1:
        cost,point=inf,0
        for i in range(n):
            if color[i]!="black" and D[i]<cost:
                cost=D[i]
                point=i

        if cost==inf:break

        color[point]="black"

        for i in range(n):
            if color[i]!="black" and M[point][i]!=inf:
                if M[point][i]<D[i]:
                    D[i]=M[point][i]
                    P[i]=point
                    color[i]="gray"

    return D


print(sum(prim(int(input()))))

Python: from sys import stdin
INF = 1<<21
WHITE, GRAY, BLACK = 0, 1, 2
n = int(stdin.readline())
M = [[INF] * n for _ in range(n)]
for i in range(0, n):
    for j, e in enumerate(list(map(int, stdin.readline().split()))):
        if e != -1: M[i][j] = e
d = [INF] * n
d[0] = 0
color = [0] * n
def prim():
    while True:
        minv = INF
        u = -1
        for i in range(0, n):
            if minv > d[i] and color[i] != BLACK:
                u = i
                minv = d[i]
        if u == -1: break
        color[u] = BLACK
        for v in range(0, n):
            if color[v] != BLACK and d[v] > M[u][v]:
                d[v] = M[u][v]
    return sum(d)
print(prim())

Python: from sys import maxsize
from functools import reduce

WHITE = 0
GRAY = 1
BLACK = 2


def read_adj_mat():
    n = int(input())
    M = []
    for _ in range(n):
        M.append([maxsize if x == "-1" else int(x)
                  for x
                  in input().split()])
    return n, M


def min_sp_tree(n, M):
    d = [maxsize] * n
    p = [-1] * n
    color = [WHITE] * n

    d[0] = 0

    while True:
        minv = maxsize
        u = -1

        for i in range(n):
            if minv > d[i] and color[i] != BLACK:
                u = i
                minv = d[i]

        if u == -1:
            break

        color[u] = BLACK
        for v in range(n):
            if color[v] != BLACK and M[u][v] != maxsize:
                if d[v] > M[u][v]:
                    d[v] = M[u][v]
                    p[v] = u
                    color[v] = GRAY

    return sum([M[i][p[i]] for i in range(n) if p[i] != -1])


def main():
    n, M = read_adj_mat()
    print(min_sp_tree(n, M))


if __name__ == '__main__':
    main()

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