题目链接:http://poj.org/problem?id=1679
题意:就是判断最小生成树是否唯一
思路:找出次小生成树,如果其权值和与MST权值和一样,便不唯一
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int fa[200], n, m;
struct edge
{
int a, b, w, fl;
edge() {}
edge(int a, int b, int w, int fl) : a(a), b(b), w(w), fl(fl) {}
bool operator < (const edge &rhs) const
{
return w < rhs.w;
}
} e[10010];
int Find(int x)
{
if(x == fa[x])
return x;
return fa[x] = Find(fa[x]);
}
int kruskal(int num)
{
int cnt = 1, ans = 0;
for(int i = 0; i < m; i++)
{
if(num == i) continue;
int fx = Find(e[i].a);
int fy = Find(e[i].b);
if(fx != fy)
{
ans += e[i].w;
cnt++;
fa[fy] = fx;
}
}
if(cnt != n)
return -1;
else
return ans;
}
void init()
{
for(int i = 0; i <= n; i++)
fa[i] = i;
for(int i = 0; i < m; i++)
e[i].fl = 0;
}
int main()
{
int t;
scanf("%d", &t);
while(t--)
{
scanf("%d%d", &n, &m);
init();
for(int i = 0; i < m; i++)
{
scanf("%d%d%d", &e[i].a, &e[i].b, &e[i].w);
}
sort(e, e + m);
int ans = 0, cnt = 1;
for(int i = 0; i < m; i++)
{
int fx = Find(e[i].a);
int fy = Find(e[i].b);
if(fx != fy)
{
e[i].fl = 1;
ans += e[i].w;
cnt++;
fa[fy] = fx;
}
}
if(cnt != n)
goto hehe;
for(int i = 0; i < m; i++)
{
if(!e[i].fl)
continue;
for(int j = 0; j <= n; j++)
fa[j] = j;
int sum = kruskal(i);
if(ans == sum)
goto hehe;
}
cout << ans << endl;
if(0)
hehe:puts("Not Unique!");
}
return 0;
}