POJ2395 Out of Hay(求最小生成树中最大的边权,Kruskal)

POJ2395 Out of Hay

寻找最小生成树中最大的边权。

使用 Kruskal 求解,即求选取的第 (n-1) 条合法边。

时间复杂度为 (O(elog e))

#include<stdio.h>
#include<string.h>
#include<algorithm>

using namespace std;

const int maxn = 10005;
int n, m, tot, f[2005];
struct edge{
    int from, to, w;
    bool operator < (const edge & _edge) const {
        return w < _edge.w;
    }
}e[maxn];

void init(){
    for(int i = 1; i <= n; i++) f[i] = i;
}
int father(int x){
    if(f[x] != x){
        f[x] = father(f[x]);
    }
    return f[x];
}
void _union(int a, int b){
    int fa = father(a), fb = father(b);
    f[fa] = f[fb];
}
int ok(int a, int b){
    int fa = father(a), fb = father(b);
    return fa == fb ? 1 : 0;
}
int main()
{
    scanf("%d%d", &n, &m);
    init();
    for(int i = 1; i <= m; i++){
        int a, b, c;
        scanf("%d%d%d", &a, &b, &c);
        e[++tot].from = a; e[tot].to = b; e[tot].w = c;
    }
    sort(e + 1, e + 1 + m);
    int cnt = 0;
    for(int i = 1; i <= m; i++){
        if(!ok(e[i].from, e[i].to)){
            _union(e[i].from, e[i].to);
            cnt++;
            if(cnt == n - 1){
                printf("%d
", e[i].w); break;
            }
        }
    }
    return 0;
}
原文地址:https://www.cnblogs.com/solvit/p/11413640.html