Description
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
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
3
Not Unique!
题目大意:
给你一个有权值的无相图,判断最小生成树是否唯一。
思路:先生成mst,存储mst的每一条边,然后枚举删除每一条mst中的边,看是否能找出一课次小生成树的权值和最小生成树的权值相等。
如果相等,则不唯一。
#include<algorithm>
#include<iostream>
#include<cstdio>
using namespace std;
const int maxn=105;
int t,n,m,tp,sum,k,ans,f[maxn],mst[maxn];
struct node
{
int x,y,val;
}a[maxn*maxn];
bool cmp(node c,node d)
{
return c.val<d.val;
}
int fnd(int x)
{
if(f[x]!=x)
f[x]=fnd(f[x]);
return f[x];
}
void pd()
{
for(int i=1;i<=n-1;i++)
{
k=0,sum=0;
for(int j=1;j<=n;j++)
f[j]=j;
for(int j=1;j<=m;j++)
if(j!=mst[i])
if(fnd(a[j].x)!=fnd(a[j].y))
{
f[fnd(a[j].y)]=fnd(a[j].x);
k++;
sum+=a[j].val;
}
if(k==n-1&&sum==ans)
{
printf("Not Unique!\n");
return ;
}
}
printf("%d\n",ans);
}
int main()
{
scanf("%d",&t);
while(t--)
{
ans=0,tp=0;
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
f[i]=i;
for(int i=1;i<=m;i++)
scanf("%d%d%d",&a[i].x,&a[i].y,&a[i].val);
sort(a+1,a+m+1,cmp);
for(int i=1;i<=m;i++)
if(fnd(a[i].x)!=fnd(a[i].y))
{
f[fnd(a[i].y)]=fnd(a[i].x);
ans+=a[i].val;
mst[++tp]=i;
}
pd();
}
return 0;
}