Description
省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可)。经过调查评估,得到的统计表中列出了有可能建设公路的若干条道路的成本。现请你编写程序,计算出全省畅通需要的最低成本。
Input
测试输入包含若干测试用例。每个测试用例的第1行给出评估的道路条数 N、村庄数目M ( < 100 );随后的 N
行对应村庄间道路的成本,每行给出一对正整数,分别是两个村庄的编号,以及此两村庄间道路的成本(也是正整数)。为简单起见,村庄从1到M编号。当N为0时,全部输入结束,相应的结果不要输出。
行对应村庄间道路的成本,每行给出一对正整数,分别是两个村庄的编号,以及此两村庄间道路的成本(也是正整数)。为简单起见,村庄从1到M编号。当N为0时,全部输入结束,相应的结果不要输出。
Output
对每个测试用例,在1行里输出全省畅通需要的最低成本。若统计数据不足以保证畅通,则输出“?”。
Sample Input
3 3 1 2 1 1 3 2 2 3 4 1 3 2 3 2 0 100
Sample Output
3 ?
解题思路
最短路问题,kruskal算法,先以权值排序结构体,寻找父节点后合并
AC代码
#include<iostream>
#include<stdio.h>
#include<algorithm>
#define MAX 101
using namespace std;
int father[MAX];
int sum,cnt;
struct Road
{
int a,b,c;
};
struct Road road[1001];
bool cmp(const Road a, const Road b) //结构体排序
{
return a.c < b.c;
}
int F_S(int x)
{
if ( x != father[x] )
father[x] = F_S( father[x] ); //寻找根节点
return father[x];
}
void Union(int a, int b, int c) //合并两个子树
{
if (a == b) return;
father[b] = a;
sum += c;
cnt++;
}
int main()
{
int n, m, i, j, k;
while (cin >> n >> m && n!=0)
{
for (i = 1; i <= m; i++) //每个节点的父节点先初始化为自身
father[i] = i;
for (i = 1; i <= n; i++)
cin >> road[i].a >> road[i].b >> road[i].c;
sort(road+1, road+n+1, cmp); //注意排序的范围
sum=0; cnt=0;
for(i = 1; i <= n; i++)
Union ( F_S(road[i].a) , F_S(road[i].b) , road[i].c );
if (cnt == m-1) //是村庄数,若有最小生成树,则合并m-1次
cout << sum << endl;
else
printf("?\n");
}
return 0;
}