程序设计思维 week6 作业D-数据中心

题目

在这里插入图片描述

Sample Input

4
5
1
1 2 3
1 3 4
1 4 5
2 3 8
3 4 2

Sample Output

4

思路

使用kruskal求最小生成树,并在求解过程中更新生成树中权值最大的边,所求即为最大权值。

代码

#include <cstdio>
#include <algorithm>
#include <vector>
using namespace std;
struct edge{
    int u,v,w;
    bool operator<(edge e)const{return w<e.w;}
}e[100005];
int n,m,root;
int father[50005];
int find(int x){return father[x]==x?x:father[x]=find(father[x]);}
bool unite(int x,int y){
    x=find(x);y=find(y);
    if(x==y)
        return false;
    father[y]=x;
    return true;
}

int kruskal(){
    sort(e,e+m);
    int count=0,ans=0;
    for(int i=0;i<m;i++){
        if(unite(e[i].u, e[i].v)){
            count++;
            ans=max(ans,e[i].w);
        }
        if(count==n-1)
            break;
    }
    return count==n-1?ans:-1;
}

int main(){
    scanf("%d%d%d",&n,&m,&root);
    for(int i=1;i<=n;i++)
        father[i]=i;
    for(int i=0;i<m;i++)
        scanf("%d%d%d",&e[i].u,&e[i].v,&e[i].w);
    printf("%d",kruskal());
    return 0;
}

题目链接

发布了24 篇原创文章 · 获赞 2 · 访问量 435

猜你喜欢

转载自blog.csdn.net/weixin_43805228/article/details/105185007