题目大意:输入两个整数m、n,分别表示道路数和村庄数。在接下来的m行中,每行有3个整数begin end weight,分别表示道路的起始村庄、结束村庄,以及修建这条道路
所需要的费用。
解题思路:最小生成树
1)题目中所指的所谓的"数据不足"其实就是指,还有孤立节点(除了根节点)。只要对其进行判断即可
for( i = 1 ; i <= n ; ++i){
if(father[i] == i){
count++;
}
}
if(count == 1){
printf("%d\n",sum);
}
2)kruscal算法的实现如下:
int kruscal(){
int i;
int sum = 0;
//初始化
for( i = 1 ; i<= n ; ++i){
father[i] = i;
}
//合并
for( i = 1 ; i <= n ; ++i){
int fx = find(e[i].begin);
int fy = find(e[i].end);
if(fx != fy){
father[fx] = fy;
sum += e[i].weight;
}
}
return sum;
}
代码如下:
/*
* 1863_1.cpp
*
* Created on: 2013年8月26日
* Author: Administrator
*/
#include <iostream>
using namespace std;
struct edge{
int begin;
int end;
int weight;
};
const int maxn = 110;
edge e[maxn*maxn];
int father[maxn];
int n;
int find(int a){
if( a == father[a]){
return a;
}
father[a] = find(father[a]);
return father[a];
}
int kruscal(){
int i;
int sum = 0;
//初始化
for( i = 1 ; i<= n ; ++i){
father[i] = i;
}
//合并
for( i = 1 ; i <= n ; ++i){
int fx = find(e[i].begin);
int fy = find(e[i].end);
if(fx != fy){
father[fx] = fy;
sum += e[i].weight;
}
}
return sum;
}
bool compare(const edge& a , const edge& b){
return a.weight < b.weight;
}
int main(){
int m;
while(scanf("%d%d",&m,&n)!=EOF,m){
int i;
memset(father,0,sizeof(father));
for( i = 1 ; i <= maxn*maxn ; ++i){
e[i].begin = -1;
e[i].end = -1;
e[i].weight = 0;
}
for(i = 1 ; i <= m ; ++i){
scanf("%d%d%d",&e[i].begin,&e[i].end,&e[i].weight);
}
sort(e + 1, e + m + 1 , compare );
int sum = kruscal();
int count = 0;
for( i = 1 ; i <= n ; ++i){
if(father[i] == i){
count++;
}
}
if(count == 1){
printf("%d\n",sum);
}else{
printf("?\n");
}
}
}