Go: package main

import (
	"fmt"
	"sort"
)

type Edge struct {
	I int
	J int
	A int
}

func main() {
	var n int
	fmt.Scan(&n)

	g := make([][]int, n)
	edges := make([]Edge, 0, n*(n-1)/2)
	parents := make([]int, n)
	for i := 0; i < n; i++ {
		g[i] = make([]int, n)
		for j := 0; j < n; j++ {
			fmt.Scan(&g[i][j])
			if g[i][j] > 0 {
				edges = append(edges, Edge{i, j, g[i][j]})
			}
		}
		parents[i] = i
	}
	sort.SliceStable(edges, func(i, j int) bool { return edges[i].A > edges[j].A })

	sum := 0
	for len(edges) > 0 {
		edge := edges[len(edges)-1]
		edges = edges[:len(edges)-1]

		if same(edge.I, edge.J, &parents) {
			continue
		}
		union(edge.I, edge.J, &parents)
		sum += edge.A
	}
	fmt.Println(sum)
}



func root(id int, parents *[]int) int {
	if id == (*parents)[id] {
		return id
	}
	return root((*parents)[id], parents)
}

func union(i, j int, parents *[]int) {
	(*parents)[root(j, parents)] = (*parents)[root(i, parents)]
}

func same(i, j int, parents *[]int) bool {
	return root(i, parents) == root(j, parents)
}

Python: n = int(input())
A = [[int(i) for i in input().strip().split(" ")] for j in range(n)]

dp1={}

for i in range(n):
    for j in range(n):
        if A[i][j] != -1 :
            dp1[(i,j)] = A[i][j]
key = []
value = []
for i,j in sorted(dp1.items(), key=lambda x:x[1]):
    key.append(i)
    value.append(j)

c_v = []
N = len(key)
len_c_v = 0
ans = 0
itr = 0
while itr != N:
    if len_c_v == n:
        break
    i = key[itr][0]
    j = key[itr][1]
    if (i in c_v) == False and (j in c_v) == False:
        c_v.append(i)
        c_v.append(j)
        ans += value[itr]
        len_c_v += 2
        itr += 1
    elif (i in c_v) == False:
        c_v.append(i)
        ans += value[itr]
        itr += 1
        len_c_v += 1
    elif (j in c_v) == False:
        c_v.append(j)
        ans += value[itr]
        itr += 1
        len_c_v += 1
    else:
        itr += 1


if len_c_v != n:
    print(-1)
else:
    print(str(ans))

Python: def Serch():
    unit = [2001]
    for j in Tree:
        for i in range(1, n):
            G[j][i] = int(G[j][i])
            if G[j][i] != -1 and i not in Tree:
                unit.append(G[j][i])
    for j in Tree:
        for i in range(1, n):
            if G[j][i] == min(unit) and i not in Tree:
                ans.append(int(G[j][i]))
                Tree.append(i)
                Serch()
                break


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

ans = []
Tree = [0]
Serch()
print(sum(ans))

Python: # input
n = int(input())
A = []
for _ in range(n):
    A.append(list(map(int, input().split())))
    
# 変数定義
inf = 100 * 2000 + 1
M = A.copy()
M = [[a if a > -1 else inf for a in line] for line in M]
d = [inf] * n
V = set([i for i in range(n)])
T = set()

# 探索
start = 0
target = start
d[target] = 0
T.add(target)
while V != T:
    for i in (V - T):
        if M[target][i] < d[i]:
            d[i] = M[target][i]

    min_wheght = min([d[i] for i in (V - T)])
    min_path = [i for i in (V - T) if d[i] == min_wheght][0]
    target = min_path
    T.add(target)

# 出力
print(sum(d))

Python: n = int(input())
A = []
for ni in range(n):
    tmp = [int(i) for i in input().split()]
    A.append([[i, t] for i, t in enumerate(tmp) if t != -1])

INF = 2001
V = [i for i in range(n)]
T = [0]
ans = 0
while len(T) != n:
    w = [-1, INF]
    for t in T:
        for a in A[t]:
            if a[1] < w[1]:
                w = a
                p = t
    ans += w[1]
    T.append(w[0])
    for ni in range(n):
        for i in range(len(A[ni])):
            if w[0] == A[ni][i][0]:
                del A[ni][i]
                break
    for ni in range(n):
        for i in range(len(A[ni])):
            if A[ni][i][0] == p:
                del A[ni][i]
                break

print(ans)

Python: #!/usr/bin/env python3


# Union find
class UnionFind:
    def __init__(self, N):
        self.N = N
        self.parent = list(range(N))

    def root(self, x):
        path_to_root = []
        while self.parent[x] != x:
            path_to_root.append(x)
            x = self.parent[x]
        for node in path_to_root:
            self.parent[node] = x  # パス圧縮
        return x

    def same(self, x, y):
        return self.root(x) == self.root(y)

    def unite(self, x, y):
        self.parent[self.root(x)] = self.root(y)

    def __str__(self):
        groups = {}
        for x in range(self.N):
            root = self.root(x)
            if root in groups.keys():
                groups[root].append(x)
            else:
                groups[root] = [x]
        result = ""
        for root in groups.keys():
            result += str(groups[root]) + "\n"
        return result


# Kruscal法: 最小全域木
# num_vertices: int
# edges=(vertex1, vertex2, weight): List[int, int, int]
# edgesについて破壊的
def kruskal(num_vertices, edges):
    total_weight = 0
    edges.sort(key=lambda e: e[2])
    u = UnionFind(num_vertices)
    for e in edges:
        x = e[0]
        y = e[1]
        weight = e[2]
        if u.same(x, y):
            continue
        u.unite(x, y)
        total_weight += weight
    return total_weight


n = int(input())
edges = []
for i in range(n):
    row = list(map(int, input().split()))
    for j in range(i, n):
        if row[j] != -1:
            edges.append([i, j, row[j]])
print(kruskal(n, edges))

Python: import itertools

n = int(input())
A = [list(map(int, input().strip().split(' '))) for _ in range(n)]
uvc = [] # A list of tuples of start, end, and cost
for i in range(n-1):
    for j in range(i+1, n):
        if A[i][j] >= 0:
            uvc.append((i, j, A[i][j]))

# コストでソート
uvc.sort(key=lambda x: x[2])

uf = list(range(n))

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

def union(x, y):
    global uf
    uf[find_root(x)] = find_root(y)

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

def costs():
    global uvc
    for u, v, c in uvc:
        if not is_same_set(u, v):
            union(u, v)
            yield c
print(sum(itertools.islice(costs(), n - 1)))