- 题目描述:
-
现在有孤岛n个,孤岛从1开始标序一直到n,有道路m条(道路是双向的,如果有多条道路连通岛屿i,j则选择最短的那条),请你求出能够让所有孤岛都连通的最小道路总长度。
- 输入:
-
数据有多组输入。
每组第一行输入n(1<=n<=1000),m(0<=m<=10000)。
接着m行,每行输入一条道路i j d(0<=d<=1000),(i,j表示岛屿序号,d表示道路长度)。
- 输出:
-
对每组输入输出一行,如果能连通,输出能连通所有岛屿的最小道路长度,否则请输出字符串"no"。
- 样例输入:
-
3 5 1 2 2 1 2 1 2 3 5 1 3 3 3 1 2 4 2 1 2 3 3 4 1
- 样例输出:
-
3 no
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <cstring>
#include <algorithm>
using namespace std;
struct edge{
int u,v,w;
};
edge e[102];
int f[102];
int find(int t){
return f[t] == t ? t : f[t] = find(f[t]);
}
bool cmp(edge a,edge b){
return a.w < b.w;
}
int main()
{
int i,n,m,a,b;
while(cin >> n >> m && n){
int ans = 0;
int en = 0;
for(i = 1;i <= n;i++)
f[i] = i;
for(i = 0;i < m;i++)
scanf("%d %d %d",&e[i].u,&e[i].v,&e[i].w);
sort(e,e + m,cmp);
for(int i = 0;i < m;i++){
int x = find(e[i].u);
int y = find(e[i].v);
if(x != y){
ans += e[i].w;
f[x] = y;
en++;
}
if(en == n - 1)
break;
}
if(en == n - 1)
cout << ans << endl;
else
cout << "?" << endl;
}
return 1;
}