题目描述
算法设计+题目分析
分析题目:
题目要求的是T_max,即每层最大值的最大值,所以要使得T_max最小,就需要使得每层的最大值最小,即要求无向图的最小生成树,然后输出其中的最大边。
算法:
使用kruskral算法求解最小生成树(并查集)
注意点+记录点
无
代码(100分)
环境
Visual C++6.0
#include <queue>
#include <stdio.h>
using namespace std;
struct Edge{//krustral算法中保存的是边集
int v1,v2,cost;
Edge(int vv1,int vv2,int c):v1(vv1),v2(vv2),cost(c){}
bool operator <(const Edge&e)const{//重载运算符
return this->cost>e.cost;//重载从大到小排列为从小到大排列
}
};
priority_queue<Edge> edges;//有序队列
int father[50005];//保存每个节点的根节点
int findFather(int x){//找到根节点
if(father[x]==x)
return x;
int temp=findFather(father[x]);
father[x]=temp;//压缩
return temp;
}
int main(){
//freopen("C:\\input.txt", "r", stdin);
int n,m,root,ans=0;
scanf("%d%d%d",&n,&m,&root);
for(int i=0; i<n; i++){//初始化
father[i]=i;
}
while(m--){
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
edges.push(Edge(a,b,c));
}
while(!edges.empty()){
Edge e=edges.top();
edges.pop();
int ua=findFather(e.v1),ub=findFather(e.v2);
if(ua!=ub){//并查集操作
father[ua]=ub;
ans=e.cost;//更新最大边
}
}
printf("%d",ans);
return 0;
}