样例输入
4
5
1
1 2 3
1 3 4
1 4 5
2 3 8
3 4 2
样例输出
4
我的注意事项:
并查集实现Kruskal
注意MAXN的数量级,MAXN表示边的最大数量(由于点的最大数量没有边多,故代码中只定义了一个最大值)
知识点区分:
//Kruskal中边的定义
struct Edge{
int from;
int to;
int length;
bool operator < (const Edge& edge) const{
return length < edge.length;
}
}
//Dijkstra中边的定义
struct Edge{
int to;
int length;
Edge(int t,int l):to(t),length(l){}
}
我的代码:
#include <iostream>
#include <algorithm>
using namespace std;
const int MAXN = 1e5;
struct Edge{
int from;
int to;
int length;
Edge(){}
Edge(int f,int t,int l):from(f),to(t),length(l){}
bool operator < (const Edge& edge) const{
return length < edge.length;
}
};
Edge edge[MAXN];
int father[MAXN];
int height[MAXN];
void init(int n){
for(int i=1;i<=n;i++){
father[i]=i;
height[i]=0;
}
}
int Find(int x){
if(father[x] != x){
father[x] = Find(father[x]);
}
return father[x];
}
void Union(int x,int y){
if(height[x] < height[y]){
father[x] = y;
}else if(height[x] > height[y]){
father[y] = x;
}else{
father[y] = x;
height[x]++;
}
}
int main(){
int n,m,root,answer=0,cnt=0;
cin>>n>>m>>root;
init(n);
for(int i=0;i<m;i++){
int from,to,length;
cin>>from>>to>>length;
edge[i] = Edge(from,to,length);
}
sort(edge,edge+m);
for(int i=0;i<m;i++){
Edge current = edge[i];
if(Find(current.from) != Find(current.to)){
Union(Find(current.from),Find(current.to));
answer = max(answer,current.length);
if(cnt++ == n-1){
break;
}
}
}
cout<<answer;
return 0;
}