Go: package main

import (
	"bufio"
	"container/heap"
	"fmt"
	"os"
	"strconv"
)

type Node struct {
	id     int
	weight int
}

func init() {
	sc.Split(bufio.ScanWords)
}

type NodeHeap []Node

func (h NodeHeap) Len() int           { return len(h) }
func (h NodeHeap) Less(i, j int) bool { return h[i].weight < h[j].weight }
func (h NodeHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }

func (h *NodeHeap) Push(x interface{}) {
	*h = append(*h, x.(Node))
}

func (h *NodeHeap) Pop() interface{} {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[0 : n-1]
	return x
}

var sc = bufio.NewScanner(os.Stdin)

func scanInt() int {
	num, _ := strconv.Atoi(scanString())
	return num
}

func scanString() string {
	sc.Scan()
	return sc.Text()
}

func init() {
	sc.Split(bufio.ScanWords)
}

func main() {
	n := scanInt()

	list := make([][]int, n)
	seen := make([]bool, n)
	for i := range list {
		list[i] = make([]int, n)
		for j := range list[i] {
			list[i][j] = scanInt()
		}
	}

	start := Node{id: 0, weight: 0}
	h := &NodeHeap{start}
	heap.Init(h)

	sum := 0
	for h.Len() > 0 {
		node := heap.Pop(h).(Node)
		if seen[node.id] {
			continue
		}
		seen[node.id] = true
		sum += node.weight

		for i, w := range list[node.id] {
			if w < 0 {
				continue
			}
			heap.Push(h, Node{id: i, weight: w})
		}
	}

	fmt.Println(sum)
}

Python: n = int(input())
m = [[-1 for i in range (n)] for j in range(n)]
d = [0]+ [2000]* (n-1)
isVisited = [False] * n


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


# def prim_mst(n):

def prim_mst(n):
  while True:
    mincost = 2000
    for i in range(n):
      if (not isVisited[i]) and (d[i] < mincost):
        mincost = d[i]
        u = i

    isVisited[u] = True

    if mincost == 2000:
      break

    for v in range(n):
      if (not isVisited[v]) and (m[u][v] != -1):
        if m[u][v] < d[v]:
          d[v] = m[u][v]
  print(d)

prim_mst(n)

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