洛谷P1111 修复公路

题目背景
A地区在地震过后,连接所有村庄的公路都造成了损坏而无法通车。政府派人修复这些公路。

题目描述
给出A地区的村庄数N,和公路数M,公路是双向的。并告诉你每条公路的连着哪两个村庄,并告诉你什么时候能修完这条公路。问最早什么时候任意两个村庄能够通车,即最早什么时候任意两条村庄都存在至少一条修复完成的道路(可以由多条公路连成一条道路)

输入格式
第1行两个正整数N,M

下面M行,每行3个正整数x, y, t,告诉你这条公路连着x,y两个村庄,在时间t时能修复完成这条公路。

输出格式
如果全部公路修复完毕仍然存在两个村庄无法通车,则输出-1,否则输出最早什么时候任意两个村庄能够通车。

输入 输出样例
输入 #1
4 4
1 2 6
1 3 4
1 4 5
4 2 3
输出 #1
5
说明/提示
N≤1000,M≤100000
x≤N,y≤N,t≤100000

先按时间排序,再用并查集来判断所有村庄是否由道路汇集成了一个连通图,代码如下

本人萌新,代码可能写的不太好...,不过还是全AC的

#include<iostream>
#include<vector>
#include<algorithm>
#include<cstdio>
#include<set>
using namespace std;

const int maxn = 10000 + 5;
int fa[maxn];

struct ss {
    int s, e, t;
};

void init(int size) {
    for (int i = 0; i <= size; i++)
        fa[i] = i;
}
int find(int x)//查找
{
    return fa[x] = fa[x] == x ? x : find(fa[x]);//路径压缩
}

bool Union(int x, int y)//合并
{
    int fx = find(x);
    int fy = find(y);
    if (fx != fy) {
        fa[fx] = fy;
        return true;
    }
    return false;
}

bool cmp(ss& a, ss& b) {
    return a.t < b.t;
}


int main() {
    int m, n;
    scanf("%d%d", &m, &n);
    init(m);
    int s, e, t;
    set<int>se;
    vector<ss>v;
    for (int i = 0; i < n; i++) {
        scanf("%d%d%d", &s, &e, &t);
        ss each;
        each.s = s; each.e = e; each.t = t;
        v.push_back(each);
    }
    sort(v.begin(), v.end(), cmp);
    int cnt = 0;
    int time;
    int i = 0;
    for (;;) {
        if (i == n)
        {
            cout << -1 << endl;
            break;
        }
        time = v[i].t;
        if (Union(v[i].s, v[i].e) == true)cnt++;
        if (cnt == m - 1) {
            cout << time << endl;
            break;
        }
        i++;
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值