1N还是畅通工程(有待优化啊)

#include <iostream>
#include <algorithm>
#include<stdio.h>
#include<math.h> 
using namespace std;
struct point
{
    int root;
}c[1001];
struct road
{
    int s,e,w;
}r[5001];
bool cmp(road x,road y)
{
    return x.w<y.w;
}
int main()
{
    int N,M,i,rr,ww,tt;
    while(scanf("%d",&N)!=EOF,N)
    {
        M=N*(N-1)/2;
        for(i=1;i<=N;i++)c[i].root=i;//初始化城镇的根 
        for(i=1;i<=M;i++)scanf("%d %d %d",&r[i].s,&r[i].e,&r[i].w);//录入边的权值信息
        sort(r+1,r+M+1,cmp);
        rr=0;ww=0;//初始化rr,ww
        for(i=1;i<=M;i++)
        {
            if(rr==(N-1))break;
            while(r[i].e!=c[r[i].e].root)
            {
                r[i].e=c[r[i].e].root;//找到根节点 
            }
            while(r[i].s!=c[r[i].s].root)
            {
                r[i].s=c[r[i].s].root;//找到根节点 
            }
            if(c[r[i].s].root<c[r[i].e].root){c[r[i].e].root=c[r[i].s].root;rr++;ww+=r[i].w;}
            else if(c[r[i].s].root>c[r[i].e].root){c[r[i].s].root=c[r[i].e].root;rr++;ww+=r[i].w;}
        }
        printf("%d\n",ww);
    }
    
    return 0;
}

总结:

1.kruskal算法以及实现

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值