畅通工程II(九度 OJ1024 )

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_37053885/article/details/88380795

畅通工程II(九度 OJ1024 )

时间限制:1 秒 内存限制:32 兆 特殊判题:否

1.题目描述:

省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可)。经过调查评估,得到的统计表中列出了有可能建设公路的若干条道路的成本。现请你编写程序,计算出全省畅通需要的最低成本。
输入描述:
测试输入包含若干测试用例。每个测试用例的第1行给出评估的道路条数 N、村庄数目M (N, M < =100 );随后的 N 行对应村庄间道路的成本,每行给出一对正整数,分别是两个村庄的编号,以及此两村庄间道路的成本(也是正整数)。为简单起见,村庄从1到M编号。当N为0时,全部输入结束,相应的结果不要输出。
输出描述:
对每个测试用例,在1行里输出全省畅通需要的最低成本。若统计数据不足以保证畅通,则输出“?”。
示例1
输入
3 3
1 2 1
1 3 2
2 3 4
1 3
2 3 2
0 100
输出
3
?

2.基本思路

该题同样是求最小生成树的代价问题,采用并查集作为基础数据结构进行求解。但该题有一个细节需要注意,就是肯能不存在最小生成树,需要针对该情况进行判断,判断的方法就是在生成结束之后检查连通分量的个数是否为1.

3.代码实现

#include <iostream>
#include <algorithm>
#define N 101
using namespace std;
int Tree[N];

struct Path{
    int city1;
    int city2;
    int cost;
}buf[N];

bool cmp(Path p1,Path p2){

    return p1.cost<p2.cost;
}

int findRoot(int x){
    if(Tree[x]==-1)return x;
    else {
        int tmp;
        tmp = findRoot(Tree[x]);
        Tree[x] = tmp;
        return tmp;
    }
}
int main()
{
    int n,m;
    int a,b;
    while(scanf("%d",&n)!=EOF){
        if(n==0)break;
        for(int i=0;i<N;i++){
            Tree[i]=-1;
        }
        scanf("%d",&m);
        for(int i=0;i<n;i++){
            scanf("%d%d%d",&buf[i].city1,&buf[i].city2,&buf[i].cost);
        }
        sort(buf,buf+n,cmp);
        int TotalCost = 0;
        for(int i=0;i<n;i++){
                int rootA = findRoot(buf[i].city1);
                int rootB = findRoot(buf[i].city2);
                if(rootA!=rootB){//若不在一个集合内
                    Tree[rootA] = rootB;//把集合A放入B中
                    TotalCost+=buf[i].cost;
                }
        }

        int cnt=0;
        for(int i=1;i<=m;i++){
            if(Tree[i]==-1){
                cnt++;
            }
        }
        if(cnt<=1)
            printf("%d\n",TotalCost);
        else//无法构成最小生成树
            printf("?\n");
    }
    return 0;
}
/*
3 3
1 2 1
1 3 2
2 3 4
1 3
2 3 2
0 100
*/

猜你喜欢

转载自blog.csdn.net/qq_37053885/article/details/88380795