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: import sys
import heapq

def main():
    n = int(input())
    next = []
    for _ in range(n):
        l = list(map(int, input().split()))
        next.append([(c, i) for i, c in enumerate(l) if c != -1])
    visited = [0] * n
    connection = 0
    q = [(0, 0)]    # (cost, v)
    heapq.heapify(q)
    ans = 0
    while len(q):
        cost, v = heapq.heappop(q)
        if visited[v]:
            continue

        # そのノードと繋げる
        visited[v] = 1
        connection += 1
        ans += cost
        
        # 新たに繋げたノードから行けるところをエンキュー
        for i in next[v]:
            heapq.heappush(q, i)
        
        # 全部のノードが繋がったら終了
        if connection == n:
            break
    print(ans)
    return

if __name__ == '__main__':
    main()

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):
    for j in range(n):
        print(adj[i][j], end=" ")
    print()

Python: N = int(input())
L = []  # input


def prim():
    # 頂点を適当に選ぶ
    s = None
    for i in range(N):
        for j in range(N):
            if L[i][j] != -1:
                s = i
                break
        if s is not None:
            break
    p = {s}
    T = []
    k = 0
    while k < N - 1:
        # 最終のP内で一番短いやつを加える
        len = float("inf")
        lenside = []
        for sg in p:
            for i in range(N):
                isT = False
                for t in T:
                    if (t[0] == sg and t[1] == i) or (t[0] == i and t[1] == sg):
                        # print("ignore")
                        isT = True
                        continue
                if isT is False and i not in p and L[sg][i] != -1 and L[sg][i] < len:
                    len = L[sg][i]
                    lenside = [sg, i]

        p.add(lenside[0])
        p.add(lenside[1])
        T.append(lenside)
        k = k + 1
        #print(p,T,k)
    cnt = 0
    for t in T:
        cnt += L[t[0]][t[1]]
    print(cnt)


for i in range(N):
    L.append(list(map(int, input().split())))
prim()

Python: import sys, collections
input = lambda: sys.stdin.readline().rstrip() 
sys.setrecursionlimit(10**7)
INF = 10**10
def I(): return int(input())
def F(): return float(input())
def SS(): return input()
def LI(): return [int(x) for x in input().split()]
def LI_(): return [int(x)-1 for x in input().split()]
def LF(): return [float(x) for x in input().split()]
def LSS(): return input().split()

class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n

    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]

    def unite(self, x, y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return

        if self.parents[x] > self.parents[y]:
            x, y = y, x

        self.parents[x] += self.parents[y]
        self.parents[y] = x

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

def kruskal(es, V):
    es.sort(key=lambda x:x[2])
    uf = UnionFind(V)
    res = 0
    for e in es:
        if not uf.same(e[0], e[1]):
            uf.unite(e[0], e[1])
            res += e[2]
    return res

def resolve():
    n = I()
    es = []
    for i in range(n):
        a = LI()
        for j in range(n):
            if a[j]!=-1:
                es.append((i, j, a[j]))

    ans = kruskal(es, n)
    print(ans)

if __name__ == '__main__':
    resolve()

Python: import heapq


def prim(adj):
    INF = 3000
    n = len(adj)
    state, d, p = [False] * n, [INF] * n, [-1] * n
    d[0] = 0
    pq = [(d[0], 0)]
    while pq:
        f, u = heapq.heappop(pq)
        state[u] = True
        if d[u] < f:
            continue
        for v, c in adj[u]:
            if state[v]:
                continue
            if c < d[v]:
                d[v] = c
                p[v] = u
                heapq.heappush(pq, (d[v], v))
    return d


def adj_matrix_to_list(matrix):
    n = len(matrix)
    li = [[] for _ in range(n)]
    for u in range(n):
        for v in range(n):
            if matrix[u][v] != -1:
                li[u].append((v, matrix[u][v]))
    return li


def main():
    n = int(input())
    m = [list(map(int, input().split())) for _ in range(n)]
    adj = adj_matrix_to_list(m)
    print(sum(prim(adj)))


if __name__ == '__main__':
    main()

Python: def main():
     def root(x):
          path=[]
          while x!=P[x]:
               path.append(x)
               x=P[x]
          for i in path:
               P[i]=x
          return x
     
     def is_same_set(x,y):
          return root(x)==root(y)
     
     def unite(x,y):
          P[root(x)]=root(y)
     
     n=int(input())
     P=[i for i in range(n)]
     edge_CostAndVertex=[]
     for i in range(n):
          cost=list(map(int,input().split()))
          for j in range(i):
               if cost[j]!=-1:
                    edge_CostAndVertex.append([cost[j],[i,j]])
                    
     edge_CostAndVertex.sort(key=lambda x:x[0])
     ans=0
     check=[]#連結されている頂点
     main_edge=edge_CostAndVertex[0][1][0]
     for i in edge_CostAndVertex:
          cost_i,a,b=i[0],i[1][0],i[1][1]
          if is_same_set(a,b):
               continue
          else:

               unite(a,b)
               ans+=cost_i
               if a not in check:
                    check.append(a)
               if b not in check:
                    check.append(b)
               if len(check)==n:
                    flag=1
                    for i in range(n):
                         for j in range(i):
                              if is_same_set(i,j):
                                   continue
                              else:
                                   flag=0
                                   break
                    if flag==1:
                         break
                    
     print(ans)
                    
if __name__=='__main__':
     main()