problem
solution
codes
#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
const int maxn = 110;
int e[maxn][maxn],ans;
struct node{
int v, w;
node(int v=0, int w=0):v(v),w(w){}
bool operator < (node b)const{return w>b.w;}
};
priority_queue<node>q;
int book[maxn];
int main(){
ios::sync_with_stdio(false);
int n; cin>>n;
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++)
cin>>e[i][j];
book[1] = 1;
for(int i = 1; i <= n; i++)
if(e[1][i])q.push(node(i,e[1][i]));
for(int i = 2; i <= n; i++){
node t = q.top(); q.pop();
while(book[t.v]){
t = q.top(); q.pop();
}
book[t.v] = 1; ans += t.w;
for(int j = 1; j <= n; j++)
if(!book[j] && e[t.v][j])
q.push(node(j,e[t.v][j]));
}
cout<<ans<<"
";
return 0;
}
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
typedef long long LL;
const int maxn = 110;
struct Edge{
int u, v, w;
Edge(int u=0, int v=0, int w=0):u(u),v(v),w(w){}
bool operator < (Edge b)const{return w<b.w;}
};
vector<Edge>e;
int fa[maxn];
void init(int n){for(int i=1;i<=n;i++)fa[i]=i;}
int find(int x){return x==fa[x]?x:fa[x]=find(fa[x]);}
void merge(int x,int y){x=find(x);y=find(y);if(x!=y)fa[x]=y;}
int main(){
int n; cin>>n;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= n; j++){
int x; cin>>x;
if(j >= i)continue;
e.push_back(Edge(i,j,x));
}
}
sort(e.begin(),e.end());
LL ans = 0;
init(n);
for(int i = 0; i < e.size(); i++){
int u = e[i].u, v = e[i].v;
if(find(u) != find(v)){
merge(u,v);
ans += e[i].w;
}
}
cout<<ans<<"
";
return 0;
}