(最小生成树)洛谷P2330 [SCOI2005]繁忙的都市

洛谷P2330 [SCOI2005]繁忙的都市

思路:

模板题。

代码:

#include<bits/stdc++.h>
#define pii pair<int,int>
#define ll long long
#define cl(x) memset(x,0,sizeof(x))
const int N=1e6+10;
const int mod=1e7+9;
const int maxn=0x3f3f3f3f;
const int minn=0xc0c0c0c0;
const int inf=99999999;
using namespace std;
struct edge
{
	int u,v,w;
}a[N];
int fa[400];
int cmp(edge x,edge y)
{
	return x.w<y.w;
}
int find(int x)
{
	if(fa[x]!=x)
		fa[x]=find(fa[x]);
	return fa[x];
}
int judge(int x,int y)
{
	int t1=find(x),t2=find(y);
	if(t1!=t2)
	{
		fa[t1]=t2;
		return 1;
	}
	return 0;
}
int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);cout.tie(0);
	int n,m,i;
	cin>>n>>m;
	for(i=1;i<=n;i++)
		fa[i]=i;
	for(i=1;i<=m;i++)
		cin>>a[i].u>>a[i].v>>a[i].w;
	sort(a+1,a+m+1,cmp);
	int count=0,ans=0;
	for(i=1;i<=m;i++)
	{
		if(judge(a[i].u,a[i].v))
		{
			count++;
			ans=max(ans,a[i].w);
		}
		if(count==n-1)
			break;
	}
	cout<<count<<" "<<ans<<endl;
	return 0;
}

发布了88 篇原创文章 · 获赞 0 · 访问量 1636

猜你喜欢

转载自blog.csdn.net/Z7784562/article/details/104079862