【最小生成树】+【并查集】-HDU-1879-继续畅通工程

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1879点击打开链接

题目描述:在畅通工程第二期的基础上增加了“有的路已经建好了这一点”。

解题思路:和这个逗比工程第二期区别不大,加几个小点进去就行了。简单。贴代码

AC代码:

#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

typedef struct Line
{
    int u;
    int v;
    int w;
};

const int MAXN=110;
int arr[MAXN];
Line lines[MAXN*MAXN/2];
int q,ans;

bool cmp(Line a,Line b)
{
    return a.w<b.w;
}

int find_father(int x)
{
    return x==arr[x]?x:arr[x]=find_father(arr[x]);
}

void mer(int a,int b)
{
    int fa=find_father(a);
    int fb=find_father(b);
    if(fa!=fb)
        arr[fa]=fb;
}

void reset()
{
    int i;
    memset(lines,0,sizeof(lines));
    q=0;ans=0;
    for(i=0;i<MAXN;i++)
        arr[i]=i;
}

int main()
{
    //freopen("hdu1879.txt","r",stdin);
    int n,i,from,to,weigh,exist;
    while(scanf("%d",&n),n)
    {
        reset();
        int nn=n*(n-1)/2;
        while(nn--)
        {
            scanf("%d%d%d%d",&from,&to,&weigh,&exist);
            if(exist)
            {
                mer(from,to);
            }
            else
            {
                lines[q].u=from;
                lines[q].v=to;
                lines[q++].w=weigh;
            }
        }
        sort(lines,lines+q,cmp);
        for(i=0;i<q;i++)
        {
            int fu=find_father(lines[i].u);
            int fv=find_father(lines[i].v);
            if(fv!=fu)
            {
                arr[fv]=fu;
                ans+=lines[i].w;
            }
        }
        printf("%d\n",ans);
    }
}

AC截图:



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值