畅通工程 最小生成树

贪心权重,几个优化点注意以下
1.提前退出的优化 我们的auto会遍历未初始化的部分
2.排序排的是边不是n(点)
又是看似正确实则错误的地方

#include <bits/stdc++.h>
using namespace std;
struct node
{
	int u,v,w;
	bool operator < (const node&it) const
	{
		return w<it.w;
	}
}e[5000];
int fa[10005];
int n,m;
int find(int x)
{
	if(fa[x]==x) return x;
	return fa[x]=find(fa[x]);//路径压缩 
}
void merge(int x,int y)
{
	fa[find(x)]=find(y);
}
int kru()
{
	int count=0;
	int ans=0;
	sort(e,e+m);//边的数量 
	for(auto it:e)
	{
		int u=it.u;int v=it.v;int w=it.w;
		if(find(u)!=find(v)) 
		{
			merge(u,v);
			ans+=w;count++;
		}
		if(count==n-1) break;//这里的优化提前退出 
	}
	return ans;
}
int main()
{
	while(cin>>n)
	{
		for(int i=1;i<=n;i++)
		{
			fa[i]=i;
		}
		memset(e,0,sizeof(e));
		if(n==0) break;
		m=n*(n-1)/2;
		for(int i=0;i<m;i++)
		{
			int uu,vv,ww;cin>>uu>>vv>>ww;
			e[i]={uu,vv,ww};
		}
		int ans=kru();
		cout<<ans<<endl;
	}
}

posted @ 2025-11-25 21:15  ll今天也要加油啊  阅读(0)  评论(0)    收藏  举报