省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可)。经过调查评估,得到的统计表中列出了有可能建设公路的若干条道路的成本。现请你编写程序,计算出全省畅通需要的最低成本。
这题比第一题多了不存在的情况
#include <iostream>
#include <string.h>
#include <stdio.h>
#include <vector>
#include <algorithm>
using namespace std;
int tree[105];
int findroot(int x){
if(tree[x] == -1) return x;
else return findroot(tree[x]);
}
struct Edge{
int a, b;
int cost;
}edge[105];
int cmp(Edge x, Edge y){
return x.cost < y.cost;
}
int main(int argc, char** argv) {
int n, m;
while(cin >> n >> m){
if(n == 0) break;
for(int i = 1; i <= n ; i++){
cin >> edge[i].a >> edge[i].b >> edge[i].cost;
}
sort(edge + 1, edge + 1 +n, cmp);
memset(tree, -1, sizeof(tree));
int ans = 0;
for(int i = 1; i <= n; i++){//对边权值按递增遍历
int a = findroot(edge[i].a);
int b = findroot(edge[i].b);
if(a != b){
tree[a] = b;
ans += edge[i].cost;
}
}
int num = 0;//集合个数
for(int i = 1; i <= m; i++){
if(tree[i] == -1) num++;
}
//集合个数大于1则说明不足以保持畅通
if(num > 1) cout << "?" << endl;
else cout << ans << endl;
}
return 0;
}