Gym-100712F-Travelling Salesman

求最小生成树的最大边
拍了个模板,然后处理每一个边的权值,每次处理一个减去一个边。因为树的边数=节点数-1,即n-1,当处理到n==1,结束

#include <bits/stdc++.h>
//#pragma comment(linker, "/STACK:102400000, 102400000")
using namespace std;
const int maxn = 100005;
struct edge{
    int u, v, w;
    bool operator < (const edge & p) const {
        return w < p.w;
    }
} edges[maxn];
int p[maxn];
int n, m;

int _find(int x){
    return p[x]==x ? x : p[x]=_find(p[x]);
}

int kruskal(){
    for (int i=1; i<=n; ++i)
        p[i] = i;
    int ans = 0;
    sort(edges, edges+m);
    for (int i=0; i<m; ++i){
        int x=_find(edges[i].u), y=_find(edges[i].v);
        if (x != y){
            ans = max(ans, edges[i].w);
            p[x] = y;
            --n;
        }
        if (n == 1)
            break;
    }
    return ans;
}

int main(){
    #ifdef LOCAL
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
    #endif
    int T;
    scanf("%d", &T);
    while (T--){
        scanf("%d%d", &n, &m);
        for (int i=0; i<m; ++i)
            scanf("%d%d%d", &edges[i].u, &edges[i].v, &edges[i].w);
        printf("%d\n", kruskal());
    }
    return 0;
}

你可能感兴趣的:(Gym-100712F-Travelling Salesman)