https://www.luogu.org/problem/show?pid=1111
模板题,复习kruskal+并查集
#include<cstdio>
#include<algorithm>
#include<cstring>
#define ms(i,j) memset(i,j, sizeof i);
using namespace std;
const int maxN = 1005, maxM = 100005;
int n,m;
int father[maxN];
struct ED
{
int x;
int y;
int t;
}edge[maxM];
bool cmp(const ED &a, const ED &b)
{
return a.t<b.t;
}
int find(int x)
{
if (x!=father[x]) return father[x] = find(father[x]);
else return father[x];
}
int merge(int r1, int r2)
{
father[r1] = r2;
}
int main()
{
scanf("%d%d", &n, &m);
for (int i=1;i<=n;i++) father[i] = i;
for (int i=1;i<=m;i++) scanf("%d%d%d", &edge[i].x, &edge[i].y, &edge[i].t);
sort(edge+1, edge+1+m,cmp);
int cnt = 0;
int tot = 0;
for (int i=1;i<=m;i++)
{
int x = find(edge[i].x);
int y = find(edge[i].y);
if (x!=y)
{
merge(x,y);
tot = max(tot, edge[i].t);
cnt++;
if (cnt==n-1)
{
printf("%d\n", tot);
return 0;
}
}
}
printf("-1\n");
return 0;
}