Given a connected undirected graph, tell if its minimum spanning tree is unique. Definition 1 (Spanning Tree): Consider a connected, undirected graph G = (V, E). A spanning tree of G is a subgraph of G, say T = (V', E'), with the following properties: 1. V' = V. 2. T is connected and acyclic. Definition 2 (Minimum Spanning Tree): Consider an edge-weighted, connected, undirected graph G = (V, E). The minimum spanning tree T = (V, E') of G is the spanning tree that has the smallest total cost. The total cost of T means the sum of the weights on all the edges in E'.
Input
The first line contains a single integer t (1 <= t <= 20), the number of test cases. Each case represents a graph. It begins with a line containing two integers n and m (1 <= n <= 100), the number of nodes and edges. Each of the following m lines contains a triple (xi, yi, wi), indicating that xi and yi are connected by an edge with weight = wi. For any two nodes, there is at most one edge connecting them.
Output
For each input, if the MST is unique, print the total cost of it, or otherwise print the string 'Not Unique!'.
Sample Input
代码语言:javascript复制2
3 3
1 2 1
2 3 2
3 1 3
4 4
1 2 2
2 3 2
3 4 2
4 1 2
Sample Output
代码语言:javascript复制3
Not Unique!
代码语言:javascript复制&:先跑一边最小生成树,然后把可以选的边存一下。如果不是唯一的话,就代表可以在剩余的边里面找到一条边可以替代已经选的边,所以枚举每一条存的边,把当前边删掉,然后在剩余里面找是否存在这样一条边,最后要判断边不能少即 k == n - 1 && res == sum ,这样就代表存在第二个最小生成树。
//#include <bits/stdc .h>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;
const int maxn = 200;
const int inf = 0x3f3f3f3f;
struct node
{
int u,v;
int w;
bool operator < (const node &x) const
{
return w < x.w;
}
} s[maxn * maxn * 10];
int fa[maxn];
int fin(int x)
{
return x == fa[x] ? x : fa[x] = fin(fa[x]);
}
int Un(int x, int y)
{
int a = fin(x);
int b = fin(y);
if(a != b)
{
fa[a] = b;
return 1;
}
return 0;
}
int vis[maxn];
int main()
{
int t,n,m;
scanf("%d",&t);
while(t--)
{
scanf("%d %d", &n, &m);
for(int i = 0; i <= n; i ) fa[i] = i;
for(int i = 0; i < m; i )
{
int u,v,w;
scanf("%d %d %d",&u,&v,&w);
s[i].u = u;
s[i].v = v;
s[i].w = w;
}
sort(s,s m);
int sum = 0;
int k = 0;
int p = 0;
int flag = 0;
for(int i = 0; i < m; i )
{
if(Un(s[i].u,s[i].v))
{
k ;
sum = s[i].w;
vis[p ] = i;
}
if(k == n-1)break;
}
for(int f = 0; f < p; f )
{
for(int i = 1; i <= n; i ) fa[i] = i;
int res = 0;
k = 0;
for(int i = 0; i < m; i )
{
if(i == vis[f])continue;
if(Un(s[i].u,s[i].v))
{
k ;
res = s[i].w;
}
}
if(res == sum && k == n-1) {
flag = 1;
break;
}
}
if(flag)printf("Not Unique!n");
else printf("%dn",sum);
}
return 0;
}