Go: package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

// I/O
type Scanner struct {
	sc *bufio.Scanner
}

func NewScanner() *Scanner {
	sc := bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)
	sc.Buffer(make([]byte, 1024), int(1e+9))
	return &Scanner{sc}
}

func (s *Scanner) nextStr() string {
	s.sc.Scan()
	return s.sc.Text()
}

func (s *Scanner) nextInt() int {
	i, e := strconv.Atoi(s.nextStr())
	if e != nil {
		panic(e)
	}
	return i
}

func (s *Scanner) nextFloat() float64 {
	f, e := strconv.ParseFloat(s.nextStr(), 64)
	if e != nil {
		panic(e)
	}
	return f
}

func (s *Scanner) nextRuneSlice() []rune {
	return []rune(s.nextStr())
}

func (s *Scanner) nextIntSlice(n int) []int {
	res := make([]int, n)
	for i := 0; i < n; i++ {
		res[i] = s.nextInt()
	}
	return res
}

func (s *Scanner) nextFloatSlice(n int) []float64 {
	res := make([]float64, n)
	for i := 0; i < n; i++ {
		res[i] = s.nextFloat()
	}
	return res
}

// Arithmetic
func max(nums ...int) int {
	m := nums[0]
	for _, i := range nums {
		if m < i {
			m = i
		}
	}
	return m
}

func min(nums ...int) int {
	m := nums[0]
	for _, i := range nums {
		if m > i {
			m = i
		}
	}
	return m
}

func abs(x int) int {
	if x > 0 {
		return x
	}
	return -x
}

func pow(x, y int) int {
	res := 1
	for i := 0; i < y; i++ {
		res *= x
	}
	return res
}

func ceil(a, b int) int {
	if a%b == 0 {
		return a / b
	} else {
		return a/b + 1
	}
}

// Sort
type RuneSlice []rune

func (a RuneSlice) Len() int           { return len(a) }
func (a RuneSlice) Less(i, j int) bool { return a[i] < a[j] }
func (a RuneSlice) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }

const INF = 1 << 60

// Main
func main() {
	sc := NewScanner()
	wtr := bufio.NewWriter(os.Stdout)
	N := sc.nextInt()
	G := make([][]int, N)
	for i := 0; i < N; i++ {
		G[i] = make([]int, N)
		for j := 0; j < N; j++ {
			G[i][j] = sc.nextInt()
		}
	}
	d := make([]int, N)
	for i := 0; i < N; i++ {
		d[i] = INF
	}
	seen := make([]bool, N)
	d[0] = 0
	ans := 0
	for {
		cur := 0
		minCost := INF
		for i := 0; i < N; i++ {
			if !seen[i] && d[i] < minCost {
				minCost = d[i]
				cur = i
			}
		}
		if minCost == INF {
			break
		}
		seen[cur] = true
		ans += d[cur]
		for i := 0; i < N; i++ {
			cost := G[cur][i]
			if cost != -1 && cost < d[i] {
				d[i] = cost
			}
		}
	}

	fmt.Fprintln(wtr, ans)
	wtr.Flush()
}

C++: #include <stdio.h>
#include <vector>
#include <list>
#include <map>
#include <array>
#include <memory>
#include <string>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <cmath>
#include <unordered_map>
#include <stdexcept>
#include <numeric>
#include <queue>

using std::string;
using std::vector;


//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// util
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

std::vector<std::string> split(const std::string& input, char delimiter)
{
    std::istringstream stream(input);

    std::string field;
    std::vector<std::string> result;
    while (std::getline(stream, field, delimiter)) {
        result.push_back(field);
    }
    return result;
}



//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// user func
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

void printList(const vector<int>& list) {
    // print
    for(int i = 0; i < list.size(); i++){
        printf("%d", list[i]);
        if ( i + 1 != list.size() ) {
            printf(" ");
        }
    }
    printf("\n");
}



//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// logic
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

// 要素数固定で汎用性低し
// index = key, value = parent key
class UnionFindTree{
private:
    vector<int> list;
public:
    UnionFindTree(int num)
        :list(num+1)
    {
        for(int i = 0; i < this->list.size(); i++) {
            list[i] = i;
        }
    }

    int Find(int key) {
        if (list[key] == key) {
            return key;
        } else {
            return Find(list[key]);
        }
    }
    bool AreSame(int lhs, int rhs){
        return Find(lhs) == Find(rhs);
    }
    void Union(int lhs, int rhs){
        this->list[Find(lhs)] = this->list[Find(rhs)];
    }

    void Print() {
        for(int i = 1; i < this->list.size(); i++) {
            printf("%d -> %d\n", i, this->list[i]);
        }
    }
};

class Node{
public:
    Node(int id, int numEdge)
     : id(id)
     , edges(vector<int>(numEdge + 1))
    {
        // constructer
    }
    void Edge(int id, int weight){
        this->edges[id] = weight;
    }
    vector<int> Edges() {
        return this->edges;
    }

    int id;
    bool done = false;
    vector<int> edges;
};

typedef struct _Relation{
    _Relation(int weight, int from, int to)
        : weight(weight)
        , from(from)
        , to(to)
    {}
    int weight;
    int from;
    int to;
} Relation;

class List{
public:
    // constructer
    List(int numNode)
    {
        this->nodes.push_back(Node(0, 0));
        for (int i = 1; i <= numNode; i++) {
            this->nodes.push_back(Node(i, numNode));
        }
    }

    void SetWeight(int from, int to, int weight)
    {
        this->nodes[from].Edge(to, weight);
    }
    
    int CalcWeight() {
        UnionFindTree tree(this->nodes.size() - 1); // init by num elements
        std::list<Relation> costs;
        for (int i = 1; i < this->nodes.size(); i++) {
            for (int j = 1; j < this->nodes[i].Edges().size(); j++) {
                int cost = this->nodes[i].Edges()[j];
                if(cost == -1) continue;
                costs.push_back(Relation(this->nodes[i].Edges()[j], i, j));
            }
        }
        costs.sort([](const Relation& lhs, const Relation& rhs){ return lhs.weight < rhs.weight; });
        vector<Relation> result;
        while(!costs.empty()) {
            auto min = costs.front();
            costs.pop_front();
            if (!tree.AreSame(min.from, min.to)) {
                tree.Union(min.from, min.to);
                result.push_back(min);
            }
        }
        int sum = 0;
        for (auto each : result) {
            sum += each.weight;
        }
        return sum;
    }
    
    

    void Print() {
        for (int i = 1; i < this->nodes.size(); i++) {
            printf("%d:", i);
            for (int j = 1; j < this->nodes[i].Edges().size(); j++) {
                printf(" %d", this->nodes[i].Edges()[j]);
            }
            printf("\n");
        }
    }
private:
    vector<Node> nodes;
};

void solve() {

    int n;
    scanf("%d", &n);
    List list(n);

    for (int i = 1; i <= n; i++){
        for (int j = 1; j <= n; j++) {
            int w;
            scanf("%d", &w);
            list.SetWeight(i, j, w);
        }
    }
    // list.Print();
    printf("%d\n", list.CalcWeight());
}

void test(){
    UnionFindTree t(5);
    t.Union(1, 2);
    t.Union(2, 3);
    t.Union(4, 5);
    t.Print();
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// main
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int main() {
    solve();
    // test();
    return 0;
}