The Unique MST
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:
- V’ = V.
- 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!
题意:
如果最短路是唯一的,输出长度,若不是,输出The Unique MST
思路:
用Kruskal算法,先把边从小到大排序,用并查集构成最小生成树,
只需要将最小生成树的边破坏一条,再求一次最小生成树就可以了。判断是否唯一
这是另一个博主写的,我的就是参考他的,咯咯咯
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <math.h>
#include <string.h>
using namespace std;
int const inf=0x3f3f3f;
int t,n,m,fa[101],add[101];//fa[]父节点,add[]记录最短树经过的边;
struct node{
int f,t,w;
}e[10001];
bool cmp(node x,node y)
{
return x.w<y.w;
}
void inti()
{
for(int i=1;i<=n;i++)
{
fa[i]=i; //初始化父节点;
}
}
int find(int x) //并查集;
{
if(x==fa[x])
return x;
return fa[x]=find(fa[x]);
}
int join(int x,int y)//合并查找;
{
int r1,r2;
r1=find(x);
r2=find(y);
if(r1!=r2)
{
fa[r2]=r1;
return 1;
}
return 0;
}
int kk(int x)//破坏最短树的边,判断(mst)是否唯一
{
int mst=0,cnt=0;
inti();
for(int i=1;i<=m;++i)
{
if(i==x)
continue;
if(join(e[i].f,e[i].t))
{
mst+=e[i].w;
cnt++;
if(x==0)
add[cnt]=i;
}
if(cnt==n-1)
return mst;
}
return -1;
}
int main()
{
scanf("%d",&t);
for(int k=1;k<=t;k++)
{
scanf("%d%d",&n,&m);
if(n==1&&m==0)
{
printf("0\n");
continue;
}
for(int i=1;i<=m;++i)
{
scanf("%d%d%d",&e[i].f,&e[i].t,&e[i].w);
}
sort(e+1,e+m+1,cmp);
int mst=kk(0);//先求出最短树的mst距离和;
bool flag=0;
for(int i=1;i<n;++i)
{
if(kk(add[i])==mst)//等于mst则不唯一;
{
printf("Not Unique!\n");
flag=1;
break;
}
}
if(!flag)
printf("%d\n",mst);
}
return 0;
}
大家要是有疑问或者本弱鸡有错误,欢迎评论,看见后一定第一时间解答