九度OJ1545题目详解

九度oj1545
题目描述:
已知一个无向带权图,求最小整数k。使仅使用权值小于等于k的边,节点1可以与节点n连通。

输入:
输入包含多组测试用例,每组测试用例的开头为一个整数n(1 <= n <= 10000),m(1 <= m <= 100000),代表该带权图的顶点个数,和边的个数。
接下去m行,描述图上边的信息,包括三个整数,a(1 <= a <= n),b(1 <= b <= n),c(1 <= c <= 1000000),表示连接顶点a和顶点b的无向边,其权值为c。

输出:
输出为一个整数k,若找不到一个整数满足条件,则输出-1。

样例输入:
3 3
1 3 5
1 2 3
2 3 2
3 2
1 2 3
2 3 5
3 1
1 2 3
样例输出:
3
5
-11
这个需要用到并查集的方法,按边的长度排序,第一次发现n与1连通时的边就是所求的k,因为已经排过序了。


实现的code:来源(http://www.cnblogs.com/easonliu/p/4429249.html)

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

struct edge_t {
    int a, b;
    int dist;
};

int n, m;
vector<edge_t> edges;
vector<int> father;

int findFather(int x) {
    while (x != father[x]) {
        x = father[x];
    }
    return x;
}

bool cmp(const edge_t &a, const edge_t &b) {
    return a.dist < b.dist;
}

void init() {
    for (int i = 0; i < father.size(); ++i) 
        father[i] = i;
    sort(edges.begin(), edges.end(), cmp);
}

void solve() {
    for (int i = 0; i < m; ++i) {
        int fa = findFather(edges[i].a);
        int fb = findFather(edges[i].b);
        if (fa < fb) father[fb] = fa;
        else father[fa] = fb;
        if (findFather(n) == 1) {
            cout << edges[i].dist << endl;
            return;
        }
    }
    cout << "-1" << endl;
}

int main() {
    while (scanf("%d %d", &n, &m) != EOF) {
        father.resize(n + 1);
        edges.resize(m);
        for (int i = 0; i < m; ++i) {
            scanf("%d %d %d", &edges[i].a, &edges[i].b, &edges[i].dist);
        }
        init();
        solve();
    }
    return 0;
}
/**************************************************************
    Problem: 1545
    User: hupo250
    Language: C++
    Result: Accepted
    Time:640 ms
    Memory:2248 kb
****************************************************************/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值