Go: package main

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

func getScanner(fp *os.File) *bufio.Scanner {
	scanner := bufio.NewScanner(fp)
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, 500001), 500000)
	return scanner
}

func getNextString(scanner *bufio.Scanner) string {
	scanner.Scan()
	return scanner.Text()
}

func getNextInt(scanner *bufio.Scanner) int {
	i, _ := strconv.Atoi(getNextString(scanner))
	return i
}

func main() {
	fp := os.Stdin
	if len(os.Args) > 1 {
		fp, _ = os.Open(os.Args[1])
	}

	scanner := getScanner(fp)
	writer := bufio.NewWriter(os.Stdout)

	n := getNextInt(scanner)

	g := make([][]int, n)
	ans := make([][]int, n)

	inf := 1 << 30
	for i := 0; i < n; i++ {
		g[i] = make([]int, n)
		ans[i] = make([]int, n)
		for ii := 0; ii < n; ii++ {
			g[i][ii] = getNextInt(scanner)
			if g[i][ii] == -1 {
				g[i][ii] = inf
			}
			ans[i][ii] = -1
		}
	}

	im := make(IntMap, 1)

	im.increment(1)

	for len(im) < n {
		min := inf
		u := -1
		v := -1
		for i := range im {
			for ii := 0; ii < n; ii++ {
				if im.get(ii) != 0 {
					continue
				}
				if min > g[i][ii] {
					min = g[i][ii]
					u = i
					v = ii
				}
			}
		}
		im.increment(v)
		ans[u][v] = min
		ans[v][u] = min
	}

	sum := 0
	for i := 0; i < n-1; i++ {
		for ii := i + 1; ii < n; ii++ {
			if ans[i][ii] != -1 {
				sum += ans[i][ii]
			}
		}
	}

	fmt.Fprintln(writer, sum)
	writer.Flush()
}

// IntMap ...
type IntMap map[int]int

func (m IntMap) get(key int) int {
	if _, ok := m[key]; ok {
		return m[key]
	}
	return 0
}
func (m IntMap) increment(key int) {
	if _, ok := m[key]; ok == false {
		m[key] = 0
	}
	m[key]++
}

Python: n = int(input())
m = []

for _ in range(n):
    tmp = [int(x) for x in input().split()]
    m.append(tmp)

#辺を全て持つリストを作る
edge_list = [] 
j = 1
for i in range(n-1):
    for k,x in enumerate(m[i][j:]):
        if x != -1:
            edge_list.append((x,i,k+j))
        else:
            pass
    j += 1
edge_list.sort()

root_list = [i for i in range(n)]

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

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

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

cost = 0
for x in edge_list:
    w,p,q = x
    if is_same_root(p,q):
        continue
    else:
        cost += w
        unite(p,q)

print(cost)

Python: inf = float("inf")
class Node():

    def __init__(self, _id):
        self.id = _id
        self.d = inf
        self.pi = None
        self.color = 0
    
    def input_data(self):
        data = [int(i) for i in input().split()]
        self.adj = {G[i]: d
                    for i, d in enumerate(data)
                    if d != -1}
    
    def __hash__(self):
        return hash(self.id)
        
    

def prim():
    G[0].d = 0
    while True:
        mincost = inf
        for i in G:
            if i.color != 1 and i.d < mincost:
                mincost = i.d
                u = i
        
        if mincost == inf:
            break

        u.color = 1
        for v in u.adj.keys():
            if v.color != 1 and u.adj[v] < v.d:
                v.pi = u.id
                v.d = u.adj[v]

if __name__ == "__main__":
    n = int(input())
    G = [Node(i) for i in range(n)]
    [i.input_data() for i in G]
    prim()
    print(sum(g.d for g in G))

Python: n = int(input())
inf = float('inf')
graphs = []

for i in range(n):
    weights = list(map(int, input().split()))
    weights = [inf if weight == -1 else weight for weight in weights]
    graphs.append(weights)
# print(graphs)
# M =graphs
color = ['WHITE' for _ in range(n)]
d = [inf for _ in range(n)]
p = [i for i in range(n)]


def prim():
    d[0] = 0
    p[0] = -1
    while True:
        min_cost = inf
        for i in range(n):
            if color[i] != 'BLACK' and d[i] < min_cost:
                min_cost = d[i]
                u = i
        if min_cost == inf:
            break
        color[u] = 'BLACK'

        for v in range(n):
            if color[v] != 'BLACK' and graphs[u][v] != inf:
                if graphs[u][v] < d[v]:
                    d[v] = graphs[u][v]
                    p[v] = u
                    color[v] = 'GRAY'


prim()
# print(d)
# print(p)
print(sum(d))

Python: def main():
    N = int(input())
    c = [[int(i) for i in input().split()] for j in range(N)]
    edges = []
    for i in range(N):
        for j in range(i+1, N):
            if c[i][j] != -1:
                edges.append((c[i][j], (i, j)))
    edges.sort()

    par = [i for i in range(N)]
    rank = [0 for i in range(N)]

    def find_root(x):
        if par[x] == x:
            return x
        else:
            par[x] = find_root(par[x])
            return par[x]

    def is_same_group(x, y):
        return find_root(x) == find_root(y)

    def unite(x, y):
        x = find_root(x)
        y = find_root(y)
        if x == y:
            return
        if rank[x] < rank[y]:
            par[x] = y
        else:
            par[y] = x
            if rank[x] == rank[y]:
                rank[x] += 1

    ans = 0
    for c, e in edges:
        if find_root(e[0]) != find_root(e[1]):
            unite(e[0], e[1])
            ans += c
    print(ans)


if __name__ == '__main__':
    main()

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)