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: class UnionFind:
    def __init__(self, n: int):
        self.nodes = n
        self.parents = [-1] * n
        self.rank = [0] * n

    # retrun the root of element x
    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]

    # unite the group include element x and group include element y
    def unite(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if x == y:
            return
        if self.rank[x] < self.rank[y]:
            self.parents[y] += self.parents[x]
            self.parents[x] = y
        else:
            self.parents[x] += self.parents[y]
            self.parents[y] = x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1

    # get size of the gourp which element x belongs
    def get_size(self, x):
        return -self.parents[self.find(x)]

    # check if element x and element y is same group
    def same(self, x, y):
        return self.find(x) == self.find(y)


def kruskal(n: int, edges: list):
    """
    n: count of nodes
    edges: list of edges, format: (node1,node2,weight)
    """
    union = UnionFind(n + 1)  # 1-indexed
    mst_sum = 0
    mst = []
    for edge in edges:
        n1, n2, w = edge
        if not union.same(n1, n2):
            union.unite(n1, n2)
            mst_sum += w
            mst.append(edge)
    return mst, mst_sum


n = int(input())
graph_table = []

for _ in range(n):
    graph_table.append([int(i) for i in input().split()])

edges = []
# edge一覧を取得
for i in range(n - 1):
    for j in range(i + 1, n):
        if graph_table[i][j] != -1:
            edges.append((i, j, graph_table[i][j]))  # node1,node2,weight

# edgeを重みの昇順にソート
edges = sorted(edges, key=lambda x: x[2])

_, mst_sum = kruskal(n, edges)
print(mst_sum)

Python: n = int(input())
a = [list(map(int, input().split())) for i in range(n)]
m = [2001] * n
f = [0] * n
sum = 0

m[0] = 0
f[0] = 1
v = 0

for i in range(n-1) :
    for j in range(n) :
        if (a[v][j] < m[j]) & (f[j] == 0) & (a[v][j] != -1):
            m[j] = a[v][j]
    
    min = 2001
    minj = 0
    for j in range(n) :
        if (m[j] < min) & (f[j] == 0):
            min = m[j]
            minj = j
    
    v = minj
    f[minj] = 1
    sum += min

print(sum)

Python: def solv(G):
  n = len(G)
  V = {0:0}
  new_V = []
  cost = 0

  while len(new_V) < n:
    u, e = min(V.items(), key=lambda x:x[1])
    V.pop(u)
    new_V.append(u)
    cost += e
    for v, e in enumerate(G[u]):
      if e < 0 or v == u or v in new_V: continue
      V[v] = min(V[v], e) if v in V else e

  return cost

n = int(input())
G = [list(map(int, input().split())) for _ in range(n)]
print(solv(G))

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
    for t in edges[vertex]:
        if not visited[t[1]]:
            heapq.heappush(queue, t)

print(total_cost)

Python: n = int(input())
m = [[-1 for i in range(n)] for j in range(n)] #お隣さんへのコストを保存（この中から最小を探す）

v = set()
v.add(0)

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):
  isVisited = [False] * n
  d = [0] + [2001] * (n-1)      #TとV-Tのを繋ぐ最小辺の重みを格納する

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


    if mincost == 2001:        #mincostが2001になったら繰り返し作業終了
      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(sum(d))

prim_mst(n)

Python: import heapq

n = int(input())
M = [list(map(int,input().split())) for _ in range(n)]

q = []

visited = [False]*n

adjs = []
sum_cost = 0
node = 0
visited[node] = True
cnt = 1

while 1:
    for i in range(n):
        if M[node][i] != -1 and visited[i] == False:
            heapq.heappush(q, (M[node][i], i))
    while 1:
        mincost,node = heapq.heappop(q)
        if visited[node] == False:
            break
    sum_cost += mincost
    visited[node] = True
    cnt += 1
    if cnt == n:
        break


print(sum_cost)

Python: N = 100

n = int(input())
adj = [[0 for i in range(n)] for j in range(n)]

for i in range(n):
    tmp = list(map(int, input().split()))
    u = tmp[0]
    u = u -1
    k = tmp[1]
    v = tmp[2:]
    for j in range(k):
        adj[u][v[j]-1] = 1
        
for i in range(n):
        print(" ".join(list(map(str, adj[i]))))

Python: import sys

n = int(sys.stdin.readline())
g = [list(map(int, sys.stdin.readline().split())) for _ in range(n)]

V = set(range(n))
U = set()
E = []

U.add(V.pop())

while len(U)<n:
    minw = 1e10
    mine = []
    for u in U:
        for v in V:
            if g[u][v]>=0 and minw>g[u][v]:
                minw = g[u][v]
                mine = [u, v]
    E.append(mine)
    U.add(mine[1])
    V.remove(mine[1])

vv=0
for u, v in E:
    vv += g[u][v]
print(vv)

Python: def prim(n, cost):
    mincost = [float("inf")]*n
    used = [False] * n
    mincost[0] = 0
    res = 0
    cnt = 1
    while True:
        u = -1
        for i in range(n):
            if (not used[i]) and (u == -1 or mincost[i] < mincost[u]):
                u = i
        if u == -1:
            break
        used[u] = True
        res += mincost[u]
        for v in range(n):
            if cost[u][v] != -1:
                mincost[v] = min(mincost[v], cost[u][v])
    return res


def main():
    n = int(input())
    g = []
    for _ in range(n):
        g.append(list(map(int, input().split())))
    print(prim(n, g))



if __name__ == '__main__':
    main()

Python: n = int(input())
edges = [[-1 for i in range(n)] for j in range(n)]

for i in range(n):
  for index, j in enumerate(list(map(int, input().split()))):
    edges[i][index] = j

inf = 9999999999999999
distances = [inf] * n
colors = ["white"] * n

def mst(u):
  distances[u] = 0
  colors[u] = "gray"

  while True:
    mincost = inf
    for i in range(n):
      if colors[i] != "black" and distances[i] < mincost:
        mincost = distances[i]
        u = i

    if mincost == inf:
      break

    colors[u] = "black"

    for index, weight in enumerate(edges[u]):
      if weight != -1 and colors[index] != "black" and distances[index] > weight:
        distances[index] = weight
        colors[index] = "gray"

mst(0)
print(sum(distances))