import java.io.BufferedInputStream;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
static int n;
static int m;
static int arr[][];
static boolean flag[];
static final int maxInt = 9999999;
public static void main(String[] args) {
Scanner s = new Scanner(new BufferedInputStream(System.in));
while(s.hasNextInt()){
n = s.nextInt();
m = s.nextInt();
if(n==0)
break;
arr = new int[m][m];
for(int i=0; i<m; i++)
Arrays.fill(arr[i], maxInt); //maxInt表示不可达
flag = new boolean[m];
for(int i=0; i<n; i++){
int a = s.nextInt() -1;
int b = s.nextInt() -1;
int c = s.nextInt();
arr[a][b] = c;
arr[b][a] = c;
}
flag[0] = true;
int sum = 0;
for(int i=1; i<m; i++){ //从第二个节点开始,进行n-1次循环
int min = maxInt;
int min_i = 0;
for(int j=0; j<m; j++){
if( !flag[j] && arr[0][j] < min ){
min = arr[0][j];
min_i = j;
}
}
flag[min_i] = true;
for(int j=0; j<m; j++){ //更新未覆盖节点距离
if( !flag[j] && arr[0][j] > arr[min_i][j])
arr[0][j] = arr[min_i][j];
}
sum += arr[0][min_i];
}
if(sum ==0 || sum>maxInt)
System.out.println("?");
else
System.out.println(sum);
}
}
}