import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
public class Main {
private static int[] parents;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Label:
while (sc.hasNextInt()) {
int n = sc.nextInt();
if (n == 0) break;
int m = sc.nextInt();
List<Edge> edges = new ArrayList<>();
while (n-- > 0) {
int from = sc.nextInt();
int to = sc.nextInt();
int cost = sc.nextInt();
edges.add(new Edge(from, to, cost));
}
edges.sort(Comparator.comparingInt(o -> o.cost));
parents = new int[m + 1];
for (int i = 1; i <= m; i++) parents[i] = i;
int ans = 0;
for (Edge edge : edges) {
if (find(edge.from) != find(edge.to)) {
parents[find(edge.from)] = find(edge.to);
ans += edge.cost;
}
}
for (int i = 1; i <= m; i++) {
if (find(i) != find(1)) {
System.out.println('?');
continue Label;
}
}
System.out.println(ans);
}
}
private static int find(int x) {
return x == parents[x] ? x : (parents[x] = find(parents[x]));
}
private static class Edge {
private final int from, to, cost;
private Edge(int from, int to, int cost) {
this.from = from;
this.to = to;
this.cost = cost;
}
}
}