P1111 修复公路
思路:很明显的最小生成树加并查集问题
ac:
#include "iostream"
#include "algorithm"
using std::cin;
using std::cout;
using std::endl;
using std::sort;
int n, m,a[1005];
struct road {
int x, y, time;
}p[10005];
int find(int x) {
if (a[x] == x)return x;
else return a[x] = find(a[x]);
}
void Union(int t1, int t2) {
a[find(t1)] = find(t2);
}
bool cmp(road a, road b) {
return a.time < b.time; //返回真按从大到小,返回假按从小到大排序
}
int main() {
cin >> n >> m;
for (int i = 1; i <= n; i++)
a[i] = i;
for (int i = 1; i <= m; i++)
{
cin >> p[i].x >> p[i].y >> p[i].time;
}
sort(p + 1, p + 1 + m, cmp);
for (int i = 1; i <= m; i++)
{
if (find(p[i].x) != find(p[i].y)) //判断这条路如果连通是否出现环
{
Union(p[i].x, p[i].y); //没出现环就联通
n--; //等到n等于1说明所有城市都连接了
}
if (n == 1)
{
cout << p[i].time; //n到1了说明城市都连接完了又因为按时间排的序所以最晚的一条路的时间就是p[i].time
return 0;
}
}
cout << -1;
return 0;
}