P1111 修复公路
思路
存下每个节点后,按时间排序,从小到大遍历,每次成功合并就cnt++,直到cnt == n就行,。
参考代码:
#include <bits/stdc++.h>
#define endl "\n"
using namespace std;
typedef long long ll;
const int maxn = 1e6 + 7;
int fa[maxn];
int find(int x)
{
return x == fa[x] ? x : fa[x] = find(fa[x]);
}
struct Node{
int x, y, t;
bool operator< (const Node & b)
{
return t < b.t;
}
} a[maxn];
signed main()
{
std::ios::sync_with_stdio(false);
std::cout.tie(0);
std::cin.tie(0);
int n, m;
cin >> n >> m;
for (int i = 1; i <= n; i++) fa[i] = i;
for (int i = 1; i <= m; i++)
cin >> a[i].x >> a[i].y >> a[i].t;
sort(a + 1, a + 1 + m);
int cnt = 1;
for (int i = 1; i <= m; i++)
{
int x = a[i].x , y = a[i].y;
x = find(x), y = find(y);
if (x != y) fa[x] = y, cnt++;
if (cnt == n){
cout << a[i].t;
return 0;
}
}
cout << -1;
return 0;
}