惠民工程(最小生成树裸题)

惠民工程
Time Limit:1000MS Memory Limit:131072KB 64bit IO Format:%lld & %llu
Submit

Status
Description
市政府“惠民工程”的目标是在全市n个居民点间之架设煤气管道(但不一定有直接的管道相连,只要能间接通过管道可达即可)。很显然最多可架设 n(n-1)/2条管道,然而实际上要连通n个居民点只需架设n-1条管道就可以了。现请你编写程序,计算出该惠民工程需要的最低成本。

Input
测试输入包含若干测试用例。每个测试用例的第1行给出居民点数目M ( < =100 )、 评估的管道条数 N;随后的 N 行对应居民点间管道的成本,每行给出一对正整数,分别是两个居民点的编号,以及此两居民点间管道的成本(也是正整数)。为简单起见,居民点从1到M编号。

Output
对每个测试用例,在1行里输出全市管道畅通所需要的最低成本。若统计数据不足以保证畅通,则输出“?”。

Sample Input
3 3
1 2 1
1 3 2
2 3 4
3 1
2 3 2
Sample Output
3
?

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <cmath>
#define MaxInt 100000
using namespace std;
struct typ{
    int q,z,w;
}eg[10005];
int fa[105];
int find(int x){
    int r=x;
    while(fa[r]!=r)
        r=fa[r];
    int i=x,t;
    while(fa[i]!=r){
        t=fa[i];
        fa[i]=r;
        i=t;
    }
    return r;
}
bool cmp(struct typ a,struct typ b){
    return a.w<b.w;
}
int main()
{
    freopen("in.txt","r",stdin);
    int m,n;
    while(~scanf("%d%d",&m,&n))
    {
        for(int i=0;i<n;i++)
        {
            scanf("%d%d",&eg[i].q,&eg[i].z);
            scanf("%d",&eg[i].w);
        }
        for(int i=0;i<=m;i++) fa[i]=i;
        sort(eg,eg+n,cmp);
        int ans=0,tot=0,flag=0;
        for(int i=0;i<n;i++){
            int f1=find(eg[i].q);
            int f2=find(eg[i].z);
            if(f1!=f2){
                fa[f1]=f2;
                tot++;ans+=eg[i].w;
                if(tot==m-1) {
                    flag=1;
                    break;
                }
            }
        }
        if(flag) cout<<ans<<endl;
        else cout<<"?"<<endl;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值