Programming thinking week6 homework D-data center

topic

Insert picture description here

Sample Input

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

Sample Output

4

Ideas

Use kruskal to find the minimum spanning tree, and update the edge with the largest weight in the spanning tree during the solution process. The maximum weight is obtained.

Code

#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;
}

Title link

Published 24 original articles · praised 2 · visits 435

Guess you like

Origin blog.csdn.net/weixin_43805228/article/details/105185007