The Unique MST
HERE
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:
- 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!
题目大意
给出一张图,判断这张图的最小生成树是不是唯一的。如果是,则输出最小权值;如果不是,则输出“Not Unique!”。
思路
- 求出最小生成树,依次替换没用过的边,用没用过的边再建立树,判断是否与最小数相等,使用并查集优化。
- 次小生成树
知识点
最小生成树
并查集
次小生成树
代码(方法一)
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
int n=0,m=0;
int node[101];
struct data
{
int u;
int v;
int w;
bool vis;
} edge[5000];
bool cmp(data a,data b)
{
return a.w<b.w?true:false;
}
int find(int x) //并查集 用于记录哪些点在树上
{
/*
循环优化
while (x!=node[x]) x=node[x]=find(node[x]);
*/
return x==node[x]?x:node[x]=find(node[x]);
}
int kruskal(int ii=-1)
{
int cnt=0,ans=0;
for (int i=1; i<=n; i++) //初始化
{
node[i]=i;
}
for (int i=0; i<m; i++)
{
if (cnt==n-1) break; //树已经建完
if (ii==i||edge[i].w==0) continue; //ii用来特判是不是最小树,edge[i].w判断是否有权为0的边
int x1=find(edge[i].u),x2=find(edge[i].v); //并查集判断是否在同一棵树
if (x1!=x2)
{
node[x1]=x2;
ans+=edge[i].w;
if (ii==-1) //ii特判是不是最小树,用来标记哪些边用过
edge[i].vis=false;
cnt++;
}
}
return ans;
}
int main()
{
int t;
cin>>t;
while (t--)
{
cin>>n>>m;
for (int i=0; i<m; i++) //存边
{
cin>>edge[i].u>>edge[i].v>>edge[i].w;
edge[i].vis=true;
}
sort(edge,edge+m,cmp);
int ans=kruskal(); //跑出最小生成树
int sum=0;
int flag=true;
for (int i=0; i<m; i++) //换边跑
{
if (edge[i].vis) //如果这条边不在最小树内,就把这条边加到树内,然后从这条边出发建树
{
continue;
}
sum=kruskal(i);
if (sum==ans)
{
cout<<"Not Unique!"<<endl;
flag=false;
break;
}
}
if (flag)
{
cout<<ans<<endl;
}
}
return 0;
}
代码(方法二)
tips:
留个坑,还有几种方法没完成。