原文链接
原题链接
解题思路
题目中的传输时间Tmax概念说的很吓人,但是其实就是生成树中最长的边长。这个题目的核心就在于求最小生成树的最长边。
代码
#include <bits/stdc++.h>
using namespace std;
struct Edge{//边的类
int v1,v2,cost;
Edge(int vv1,int vv2,int c):v1(vv1),v2(vv2),cost(c){}
bool operator <(const Edge&e) const{
return cost > e.cost;//根据费用进行排序
}
};
int n,m,root,ans=0;
priority_queue <Edge> edges;//用队列存放边,自动排序
int father[50005];
//查找父亲节点
int findfather(int x){
//查找根节点,并进行路径压缩
int son = x,root = x;
while(root != father[root]){
root = father[root];//查找根节点
}
//将所有root作为所有孩子节点的直接父亲
while(son != root){
int tmp = father[son];
father[son] = root;
son = tmp;
}
return root;//返回父亲节点
}
int main(){
scanf("%d%d%d",&n,&m,&root);
for(int i=1;i<=n+10;i++){
father[i] = i;
}
while(m--){
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
edges.emplace(a,b,c);
}
while(!edges.empty()){
Edge e = edges.top();
edges.pop();
int fa = findfather(e.v1);
int fb = findfather(e.v2);
if(fa != fb){
father[fa] = fb;
ans = e.cost;//更新最长边
}
}
printf("%d",ans);
return 0;
}