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

C++: #include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;

const long INF=1000000000;

int main(){
	int n;
	long a[100][100];
	
	scanf(" %d", &n);
	for(int i=0; i<n; ++i){
		for(int j=0; j<n; ++j){
			long p;
			scanf(" %ld", &p);
			if(p==-1) a[i][j]=INF;
			else a[i][j]=p;
		}
	}
	
	//prim
	
	int visit[100]={0}; //????¨??????§?????????
	
	int p[100]; //MST???????????????
	p[0]=-1;
	
	int d[100];
	for(int i=0; i<n; ++i) d[i]=INF;
	d[0]=0; //????????????0???????????????????????????
	
	int u;
	while(1){
		long mincost=INF;
		
		for(int i=0; i<n; ++i){
			if(visit[i]!=-1 && d[i]<mincost){
				mincost=d[i];
				u=i;	
			}
		}
		
		if(mincost==INF) break; //????????\?????????????????????
		
		visit[u]=-1; //?¨??????????
		
		for(int i=0; i<n; ++i){
			if(visit[i]!=-1 && a[u][i]<d[i]){
				d[i]=a[u][i];
				p[i]=u;
				visit[i]=1; //?¬??¨???????????\´???????£?
			}
		}
		
	}
	
	long ans=0;
	for(int i=0; i<n; ++i){
		if(p[i]!=-1) ans+=a[i][p[i]];
		
	}
	printf("%ld\n", ans);
}