Problem : 1863 ( 畅通工程 ) Judge Status : Accepted
RunId : 2690792 Language : G++ Author : huwenbiao
Code Render Status : Rendered By HDOJ G++ Code Render Version 0.01 Beta
RunId : 2690792 Language : G++ Author : huwenbiao
Code Render Status : Rendered By HDOJ G++ Code Render Version 0.01 Beta
/***************************************************************\
*Author:Hu Wenbiao
*Created Time: Mon 26 Jul 2010 08:09:32 PM CST
*File Name: main.cpp
*Description:最小生成树。Kruscal算法
\***************************************************************/
//*========================*Head File*========================*\\
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<algorithm>
#include<string.h>
/*----------------------*Global Variable*----------------------*/
int parent[110],N,M,sum;
struct Edge{
int from,to,dis;
}edge[110];
//*=======================*Main Program*=======================*//
using namespace std;
bool cmp(Edge a,Edge b){
return a.dis<b.dis;
}
int find(int x){
if(parent[x]>0)
parent[x]=find(parent[x]);
return parent[x]>0?parent[x]:x;
}
void union_set(int x,int y){
x=find(x),y=find(y);
if(parent[x]<parent[y]){
parent[x]+=parent[y];
parent[y]=x;
}
else{
parent[y]+=parent[x];
parent[x]=y;
}
}
int main(){
//freopen("input","r",stdin);
while(scanf("%d%d",&N,&M)!=EOF&&N){
for(int i=0;i<N;i++){
scanf("%d%d%d",&edge[i].from,&edge[i].to,&edge[i].dis);
}
if(M>N+1){//剪枝
printf("?\n");
continue;
}
sum=0;
memset(parent,-1,sizeof(parent));
sort(edge,edge+N,cmp);
for(int i=0;i<N;i++){
int x=find(edge[i].from),y=find(edge[i].to);
if(x!=y){
union_set(x,y);
sum+=edge[i].dis;
M--;
}
}
if(M==1)
printf("%d\n",sum);
else
printf("?\n");
}
}