题目链接
本题和还是畅通工程思路非常类似。
区别在于后者给的图的边数为n*(n-1)/2,是一个无向完全图,一定能找到一个最小生成树。而前者给的边数不定,所以不一定能生成一个最小生成树,需要判断。
所用知识点:kruskal算法(最小生成树) 并查集
代码如下:
#include <iostream>
#include<stdio.h>
#include<algorithm>
using namespace std;
struct edge {
int a, b;
int cost;
bool operator <(const edge &b) const {//将边以权值从小到大的形式排
return cost < b.cost;
}
}buf[5000];
int tree[100];
int find(int x) {//之前写成递归形式会爆栈,所以写成非递归
int ret;
int tmp=x;
while (tree[x] != -1) x = tree[x];
ret = x;
x = tmp;
while (tree[x] != -1)
{
int t = tree[x];
tree[x] = ret;
x = t;
}
return ret;
}
int main()
{
int n;
while (cin >> n) {
if (n == 0) break;
int m;
cin >> m;
for (int i = 0;i < n;i++)
cin>> buf[i].a >> buf[i].b >> buf[i].cost;
for (int i = 1;i <= m;i++) tree[i] = -1;
sort(buf, buf + n);
int ans = 0;
int count = 0;
for (int i = 0;i < n;i++)
{
int a = find(buf[i].b);
int b = find(buf[i].a);
if (a != b) {
tree[a] = b;
ans += buf[i].cost;
}
}
for (int i = 1;i <= m;i++)
{
if (tree[i] == -1) count++;//用联通分量来判断是否合成了一个最小生成树。
}
if (count == 1) cout << ans << endl;
else cout << "?" << endl;
}
return 0;
}