样例输入
4
5
1
1 2 3
1 3 4
1 4 5
2 3 8
3 4 2
样例输出
4
样例说明
下图是样例说明。
解题思路:
题目要求每个节点需要选择一条路径将数据发送到root号节点,即要求图中所有节点连通,root节点不用管,没有实际
作用,只需要找出最小支撑树中最大的边长即可。
采用Kruskal算法 但不知道到为什么自己测试过了却没有分(奇怪qaq)
#include <iostream>
#include <algorithm>
using namespace std;
struct node
{
int head;
int tail;
int cost;
};
int cmp(node & a,node & b)
{
return a.cost<b.cost;
}
int Find(int x,int * Make_set)
{
int r=x;
if(x!=Make_set[x])
{
x=Make_set[x];
}
int s;
while(r!=x)
{
s=Make_set[r];
Make_set[r]=x;
r=s;
}
return x;
}
void Union(int a,int b,int * rank,int * Make_set)
{
int x=Find(a,Make_set);
int y=Find(b,Make_set);
if(rank[x]<rank[y])
{
Make_set[x]=y;
}
else if(rank[x]>rank[y])
{
Make_set[y]=x;
}
else
{
rank[x]++;
Make_set[y]=x;
}
}
int main()
{
int n;
cin>>n;
int m;
cin>>m;
int root;
cin>>root;
node E[m];
node TE[n-1];
for(int i=0;i<m;i++)
{
cin>>E[i].head>>E[i].tail>>E[i].cost;
}
sort(E,E+m,cmp);
int count=0;
int Make_set[n+1];
int rank[n+1]={0};
for(int i=1;i<=n;i++)
{
Make_set[i]=i;
}
int T=n;
int j=0;
while(T>1)
{
int a=E[j].head;
int b=E[j].tail;
int c=E[j].cost;
if(Find(a,Make_set)!=Find(b,Make_set))
{
TE[count].head=a;
TE[count].tail=b;
TE[count].cost=c;
count++;
Union(a,b,rank,Make_set);
T--;
j++;
}
}
cout<<TE[n-2].cost;
int yu;
cin>>yu;
return 0;
}