3
?
AC代码:
#include<stdio.h>
#include<algorithm>
using namespace std;
int p[101];
struct Road {
int start;
int end;
int cost;
bool operator < (const Road &b) const {
return cost < b.cost;
}
}roads[100];
int findRoot(int x) {
if(p[x]==-1)
return x;
else {
int tmp = findRoot(p[x]);
p[x] = tmp;
return tmp;
}
}
int Kruscal(Road r[], int n, int m) {
int a, b, j, t=0, sum=0;
sort(r,r+n);
for(j=0; j<n; j++) {
a = findRoot(r[j].start);
b = findRoot(r[j].end);
if(a!=b) {
p[b] = a;
sum += r[j].cost;
t++;
}
}
if(t == m-1)
return sum;
else
return -1;
}
int main() {
//freopen("in.txt","r",stdin);
int n, m;
while(scanf("%d %d",&n,&m)!=EOF && n) {
int i;
for(i=1; i<=m; i++) {
p[i] = -1;
}
for(i=0; i<n; i++) {
scanf("%d %d %d",&roads[i].start,&roads[i].end,&roads[i].cost);
}
int minCost = Kruscal(roads,n,m);
if(minCost >= 0)
printf("%d\n",minCost);
else
printf("?\n");
}
return 0;
}