#include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> p;
typedef struct edge edge; //结构体重命名
struct edge{int from;int to;int cost;}eg[100];//结构体数组存边
bool cmp(edge x,edge y){ //比较函数
if(x.cost<=y.cost)return true;//小数优先
else return false; //大数在后
}
int fa[103]; //父亲数组
int find(int x){ //找X的祖先
if(x==fa[x])return x; //X为根就返回自身
return fa[x]=find(fa[x]);//否则就返回他父亲的祖先
}
int main() {
for(int i=0;i<=100;i++)fa[i]=i; //初始化全部为根
int n,e;cin>>n>>e; //N个点,E条边
for(int i=1;i<=2*e;i+=2){ //因为是双向边,所有有2E条
int a,b,c;cin>>a>>b>>c; //输出起,终,权
eg[i]=edge{a,b,c}; //正向存边
eg[i+1]=edge{b,a,c}; //反向存边
}
sort(eg+1,eg+1+2*e,cmp); //升序
int tot=0,flag=0; //TOT是总答案,FLAG是当前连了多少条边
for(int i=1;i<=2*e;i++){ //输出两条边
edge tpe=eg[i]; //读出第I条边
if(find(tpe.from)==find(tpe.to))continue;//如果两边的祖先一样,已连通就跳出
fa[find(tpe.from)]=find(tpe.to);//把其中一根定为另一根的祖先连起来(此处没考虑秩)
tot+=tpe.cost; //花费累加
flag++; //标记加1
if(flag==n-1){ //因为有N个点,连了N-1条就结束
cout<<tot<<endl;//输出答案
return 0;
}
}
cout<<"impossible"<<endl;//走到这里就是不可能
return 0;
}
/*
4 6
1 2 6
1 3 5
1 4 4
2 3 3
2 4 2
3 4 1
*/
Kruskal
最新推荐文章于 2025-05-14 16:25:01 发布