题目描述
Sample Input
4
5
1
1 2 3
1 3 4
1 4 5
2 3 8
3 4 2
Sample Output
4
算法/思路分析
题意翻译成图语言就是在图中找一个生成树,使得该树的最大边权相对于其他生成树最小。
按照Kruskal算法的思想,我们可以每次选择成本最小的边,若合法,则合并,合并后我们可以记录/更新该生成树的最大边权,最终,我们记录的最大边权即为所有生成树中的最小值。
代码
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>
#include <cmath>
using namespace std;
const int maxn = 1e5+10;
#define ll long long
struct edge
{
int u,v,w;
bool operator<(const edge &p)const
{
return w < p.w;
}
}e[maxn];
int par[maxn], rnk[maxn];
int n,m,root;
void init()
{
for(int i = 0; i <= n; i++)
{
par[i] = i;
rnk[i] = 1;
}
}
int find(int x)
{
return par[x] == x ? x : par[x] = find(par[x]);
}
bool unite(int x,int y)
{
x = find(x); y = find(y);
if(x == y) return false;
if(x < y) swap(x,y);
par[x] = y;
rnk[y] += rnk[x];
rnk[x] = rnk[y];
return true;
}
int main()
{
scanf("%d%d%d",&n,&m,&root);
for(int i = 0; i < m; i++)
scanf("%d%d%d",&e[i].u,&e[i].v,&e[i].w);
sort(e,e+m);
init();
int ans = 0;
int cnt = 0;
for(int i = 0; i < m; i++)
{
int u = e[i].u;
int v = e[i].v;
int w = e[i].w;
if(unite(u,v))
{
ans = max(ans,e[i].w);
if(cnt == n) break;
cnt++;
}
}
printf("%d",ans);
return 0;
}