Week6 Assignment-D-Data Center

topic

Insert picture description here

Example

Input

4
5
1
1 2 3
1 3 4
1 4 5
2 3 8
3 4 2

Output

4

Note

Insert picture description here

Ideas

Review questions

Insert picture description here

Insert picture description hereAccording to the meaning of the question, find a spanning tree where the maximum edge weight of all edges is the smallest. According to the nature of the minimum spanning tree is the bottleneck spanning tree, it is transformed into the problem of finding the minimum spanning tree, and the largest edge is saved in ans.

Code

#include<iostream>
#include<algorithm> 
using namespace std;
const int N=50005;
const int M=100005;
struct edge
{
    
    
	int u,v,w;
	bool operator<(const edge &t) const
	{
    
    
		return w<t.w;
	}
}e[M];
int n,m,rt;
int f[N];
void init(int n)
{
    
    
	for(int i=1;i<=n;i++)
		f[i]=i;
}
int find(int x)
{
    
    
	if(f[x]==x)
		return x;
	return f[x]=find(f[x]);
}
bool unite(int x,int y)
{
    
    
	x=find(x);
	y=find(y);
	if(x==y)
		return false;
	f[x]=y;
	return true;
}
int kruskal_return_max()
{
    
    
	sort(e,e+m);
	int cnt=0,ans=0;
	for(int i=0;i<m;i++)
	{
    
    
		if(unite(e[i].u,e[i].v))
		{
    
    
			ans=max(ans,e[i].w);
			if(++cnt==n-1)
				break;
		}
	}
	return cnt==n-1?ans:-1;
} 
int main()
{
    
    
	scanf("%d%d%d",&n,&m,&rt);
	init(n);
	for(int i=0;i<m;i++)
		scanf("%d%d%d",&e[i].u,&e[i].v,&e[i].w);
	printf("%d\n",kruskal_return_max());
		
	return 0;
}

Guess you like

Origin blog.csdn.net/alicemh/article/details/105259247