#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<iostream>
using namespace std;
struct node{
int x,y,w;
}e[5050];
int n,m,father[5050];
int cmp(node a,node b){
return a.w<b.w;
}
int findroot(int p){
if(father[p]!=p)
father[p]=findroot(father[p]);
return father[p];
}
void unionset(int p,int q){
father[q]=p;
}
int kruskal(){
int res=0,k=1,j=0;
for(int i=1;i<=m;i++)
father[i]=i;
while(k<n&&j<m){
int m1=e[j].x,m2=e[j].y;
int sn1=findroot(m1),sn2=findroot(m2);
if(sn1!=sn2){
res+=e[j].w;k++;
unionset(sn1,sn2);
}
j++;
}
if(k!=n)res=-1;
return res;
}
int main(){
while(scanf("%d%d",&m,&n)!=EOF){
if(m==0)break;
for(int i=0;i<m;i++){
scanf("%d%d%d",&e[i].x,&e[i].y,&e[i].w);
}
sort(e,e+m,cmp);
int ans=kruskal();
if(ans==-1)printf("?\n");
else printf("%d\n",ans);
}
return 0;
}
测试
输入
3 3 1 2 1 1 3 2 2 3 4 1 3 2 3 2 0 100输出
3 ?