1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// Author: Adam Krasuski

#include <cstdio>
#include <vector>
#include <queue>

using namespace std;

struct edge{
    int from;
    int to;
    int cost;
};

int operator<(edge a,edge b){
    if(a.cost!=b.cost){
        return a.cost>b.cost;
    }
    if(a.from<b.from){
        return a.from>b.from;
    }
    return a.to>b.to;
}

vector<edge> edges[2009];//n+1
int visited[2009];

int main(){
    int n;
    scanf("%d",&n);
    for(int i=0;i<n;i++){
        for(int j=0;j<n-i;j++){
            int cost;
            scanf("%d",&cost);
            edge ed={i,i+j+1,cost};
            edges[i].push_back(ed);
            ed.from=i+j+1;
            ed.to=i;
            edges[i+j+1].push_back(ed);
        }
    }
    //prime's algorithm
    vector<edge> chosen_edges;
    priority_queue<edge> possible_edges;
    visited[0]=1;
    for(int i=0;i<edges[0].size();i++){
        possible_edges.push(edges[0][i]);
    }
    while(chosen_edges.size()<n){
        edge next=possible_edges.top();
        possible_edges.pop();
        if(visited[next.to]){
            continue;
        }
        //else, add the edge to chosen ones
        visited[next.to]=1;
        chosen_edges.push_back(next);
        int vert=next.to;
        for(int i=0;i<edges[vert].size();i++){
            if(!visited[edges[vert][i].to])
                possible_edges.push(edges[vert][i]);
        }
    }
    //adding the costs of chosen edges
    long long int total_cost=0;
    for(int i=0;i<chosen_edges.size();i++){
        total_cost+=(long long int)chosen_edges[i].cost;
    }
    printf("%lld\n",total_cost);





}