[Ybtoj Chapter 11 Example 1] Busy City [Minimum Spanning Tree]

Insert picture description here
Insert picture description here
Insert picture description here
Insert picture description here
Insert picture description here


Problem-solving ideas

For the minimum spanning tree template question, both prim and kruskal can be used. This question directly tells us the side, and kruskal is more convenient to be greedy by side.

Blog recommendation:

PS: I think it’s the most commonly used.


Code

#include<iostream>
#include<cstdio>
#include<iomanip>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<bitset>
using namespace std;

int n,m,x,y,w,ans,k,fa[310];

struct c{
    
    
	int x,y,w;
}a[310];

bool cmp(c l,c r)
{
    
    
	return l.w<r.w;
}

int find(int x)
{
    
    
	if(x==fa[x])return x;
	else return fa[x]=find(fa[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].w);
	sort(a+1,a+m+1,cmp);
	for(int i=1;i<=n;i++)	
		fa[i]=i;
	printf("%d ",n-1);
	for(int i=1;i<=m;i++)
	{
    
    
		int p=find(a[i].x),q=find(a[i].y);
		if(p!=q)
		{
    
    
			fa[p]=q;
			ans=max(ans,a[i].w);
			k++;
			if(k==n-1)
			{
    
    
				printf("%d",ans);
				return 0;	
			}
		}
	}
}

Guess you like

Origin blog.csdn.net/kejin2019/article/details/115259000