Kruskal裸题嘻嘻
不说了
Code:
#include<cstdio>
#include<cstdlib>
#include<iostream>
#include<algorithm>
using namespace std;
struct node{
int x,y,c;
inline bool operator <(const node &b)const
{
return c<b.c;
}
}a[100010];
int n,m,f[1010];
inline int findfa(int x)
{
if(f[x]==x) return x;
return f[x]=findfa(f[x]);
}
int main()
{
scanf("%d %d",&n,&m);
for(int i=1;i<=m;i++)
scanf("%d %d %d",&a[i].x,&a[i].y,&a[i].c);
sort(a+1,a+1+m);
int tot=0,ans=0;
for(int i=1;i<=n;i++) f[i]=i;
for(int i=1;i<=m;i++)
{
int fx=findfa(a[i].x),fy=findfa(a[i].y);
if(fx!=fy)
{
f[fx]=fy;
tot++;
ans=max(ans,a[i].c);
}
if(tot==n-1) break;
}
if(tot<n-1) printf("-1");
else printf("%d",ans);
}

本文通过一道具体的题目实例,详细介绍了使用Kruskal算法解决最小生成树问题的过程。包括读取边的权重、进行排序,并利用并查集来确定哪些边可以加入最终的最小生成树中,最终输出最小生成树的最大边权重。
378

被折叠的 条评论
为什么被折叠?



