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!
题意是求一个图的最小生成树是否唯一。
思路就是求出次小生成树,判断次小生成树的权值与最小生成树是否相等。次小生成树的求法是枚举最小生成树的每条边,把其中一条边去掉,找到这两点上其他的边,剩下的边形成最小生成树
#include <iostream>
#include <algorithm>
#include <cstdio>
#define MAXN 105
using namespace std;
struct Node
{
int x,y,w;
bool flag;
};
Node edge[MAXN*MAXN];
bool cmp(Node a,Node b)
{
return a.w<b.w;
}
int n,m,father[MAXN];
int kruskal(int num,int m)
{
int ans=0,cnt=1;
for(int i=1; i<=m; ++i)
{
if(i==num) //把第一棵最小生成数的第num边去掉
continue;
int s1=father[edge[i].x];
int s2=father[edge[i].y];
if(s1!=s2)
{
cnt++;
ans+=edge[i].w;
father[s2]=s1; //加入生成树的边,加入相同的并查集
for(int j=0; j<=n; ++j)
if(father[j]==s2)
father[j]=s1;
}
}
if(cnt!=n)
return -1;
else
return ans;
}
int main()
{
int t,ans;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);
for(int i=1; i<=n; ++i)
father[i]=i;
for(int i=1; i<=m; ++i)
{
scanf("%d%d%d",&edge[i].x,&edge[i].y,&edge[i].w);
edge[i].flag=false;
}
sort(edge+1,edge+1+m,cmp);
ans=0;
for(int i=1; i<=m; ++i)
{
int s1=father[edge[i].x];
int s2=father[edge[i].y];
if(s1!=s2)
{
edge[i].flag=true; //最小生成数做记号
ans+=edge[i].w;
father[s2]=s1;
for(int j=0; j<=n; ++j)
if(father[j]==s2)
father[j]=s1;
}
}
bool flag=0;
for(int i=1; i<=m; ++i) //枚举最小生成树的每条边
{
if(edge[i].flag==false)
continue;
int sum=0;
for(int j=1; j<=n; ++j)
father[j]=j;
sum=kruskal(i,m); //把第i条边去掉
if(sum==ans)
{
flag=true;
break;
}
}
if(flag)
printf("Not Unique!\n");
else
printf("%d\n",ans);
}
return 0;
}