最小生成树
#include <iostream>
#include <algorithm>
using namespace std;
struct Node
{
int a, b, cost;
};
bool cmp(Node x, Node y)
{
return x.cost < y.cost;
}
Node list[101];
int tree[101];
int findRoot(int x)
{
if(tree[x] == x)
return x;
int tmp = findRoot(tree[x]);
tree[x] = tmp;
return tmp;
}
int main()
{
int n, m, a, b, cost;
while(cin >> n >> m && n != 0)
{
for(int i = 1; i <= m; i++)
tree[i] = i;
for(int i = 0; i < n; i++)
cin >> list[i].a >> list[i].b >> list[i].cost;
sort(list, list+n, cmp);
int ans = 0;
for(int i = 0; i < n; i++)
{
int a = findRoot(list[i].a);
int b = findRoot(list[i].b);
if(a != b)
{
tree[a] = b;
ans += list[i].cost;
}
}
int cnt = 0;
for(int i = 1; i <= m; i++)
{
if(tree[i] == i)
cnt++;
}
if(cnt > 1)
cout << "?" << endl;
else
cout << ans << endl;
}
return 0;
}