试题编号:201812-4 试题名称:数据中心


样例输入

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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值