POJ1679 K - The Unique MST (最小生成树是否唯一)
程序员文章站
2024-03-21 17:36:58
...
判断最小生成树是否唯一。
先找出最小生成树,并记录组成,然后循环去掉一个组成,判断剩下的边能否构成最小生成树。
#include <cstdio>
#include <algorithm>
using namespace std;
const int maxn = 110;
const int maxm = maxn * maxn;
int par[maxn];
int ans[maxn];
struct edgs {
int from, to, cost;
bool operator < (const edgs& a) const {
return cost < a.cost;
}
}edg[maxm];
int find(int x)
{
return x == par[x] ? x : par[x] = find(par[x]);
}
int main(void)
{
int t;
scanf("%d", &t);
while (t--) {
int n, m, k = 1, cnt = 0, tot = 0, flag = 1;
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++) par[i] = i;
for (int i = 1; i <= m; i++) {
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
edg[k].from = a;
edg[k].to = b;
edg[k++].cost = c;
}
sort(edg + 1, edg + k);
for (int i = 1; i < k; i++) {
int rf = find(edg[i].from);
int rt = find(edg[i].to);
if (rf == rt) continue;
par[rf] = rt;
ans[++cnt] = i;
tot += edg[i].cost;
if (cnt == n - 1) break;
}
for (int i = 1; i <= cnt; i++) {
int sum = 0, p = 0;
for (int j = 1; j <= n; j++) par[j] = j;
for (int j = 1; j < k; j++) {
if (ans[i] == j) continue;
int rf = find(edg[j].from);
int rt = find(edg[j].to);
if (rf == rt) continue;
par[rf] = rt;
sum += edg[j].cost;
if (++p == n - 1) break;
}
if (p == n - 1 && sum == tot) {
printf("Not Unique!\n");
flag = 0;
break;
}
}
if (flag) printf("%d\n", tot);
}
return 0;
}