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<iostream>
#include<vector>
#include<algorithm>
#define INFTY 10000
#define PII pair<int,int>
#define MPII(a,b) make_pair(a,b)
using namespace std;
class NODE
{
public:
	vector<PII> v;
	int index = 0;
	bool Isdone = false;
};
class Tree
{
public:
	vector<int> V;
	int cost = 0;
};

int main()
{
	NODE* nodes;
	nodes = new NODE[101];
	Tree T;
	int n;
	cin >> n;
	for (int i = 1; i <= n; i++)
	{
		for (int j = 1; j <= n; j++)
		{
			int t;
			cin >> t;
			if (t != -1)
			{
				PII p = MPII(t, j);
				nodes[i].v.push_back(p);
			}
		}
		sort(nodes[i].v.begin(), nodes[i].v.end());
	}
	T.V.push_back(1);
	nodes[1].Isdone = true;
	while (1)
	{
		if (T.V.size() == n)break;
		int mincost=INFTY;
		int addv=-1;
		int index;
		for (auto itr : T.V)
		{
			if (nodes[itr].v.size() <= nodes[itr].index)continue;
			while (1)
			{
				if (nodes[nodes[itr].v[nodes[itr].index].second].Isdone == false)break;
				nodes[itr].index++;
				if (nodes[itr].v.size() <= nodes[itr].index)break;
			}
			if (nodes[itr].v.size() <= nodes[itr].index)continue;
			if (mincost >= nodes[itr].v[nodes[itr].index].first)
			{
				mincost = nodes[itr].v[nodes[itr].index].first;
				addv = nodes[itr].v[nodes[itr].index].second;
				index = itr;
			}
		}
		
		nodes[index].index++;
		T.V.push_back(addv);
		nodes[addv].Isdone = true;
		T.cost += mincost;
	}
	cout << T.cost << endl;
	delete[] nodes;
	return 0;
}