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:
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!
题目大意
问你最小生成树是否唯一。思路很简单,就是求出最小生成树
以及次小生成树
,然后比较两者是否一样大
,若一样大,那么就不唯一,反之则唯一。
那么问题来了,怎么求次小生成树呢?
其实也很简单,就比求最小生成树多了两点
1.求出最小生成树,并且把最小生成树用到的边
都标记一下
2.选择最小生成树所用到的一条边
,然后求出不用这条边
的情况下,生成的最小生成树是否和用这条边的最小生成树一样。将最小生成树的每条边都遍历一遍,只要有一条边满足上述条件,最小生成树就不唯一!*
代码
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <vector>
#include <map>
#include <stack>
#include <list>
#include <set>
#include <queue>
#include <string>
#include <string.h>
using namespace std;
int n, m, ans, num;
struct edge
{
int a, b, len, IS;
} p[1000005];
int pre[1000005];
void intt()
{
for (int i = 1; i <= n; i++)
pre[i] = i;
}
int find(int x)
{
if (pre[x] == x)
return x;
return pre[x] = find(pre[x]);
}
bool cmp(edge a, edge b)
{
return a.len < b.len;
}
int kruskal(int x) //求出去掉第x条边之后的最小生成树的值sum
{
int ct = 0;
intt();
int sum = 0;
for (int i = 0; i < m; i++)
{
if (i == num)
continue;
if (find(p[i].a) != find(p[i].b))
{
pre[find(p[i].a)] = find(p[i].b);
sum += p[i].len;
ct++;
}
if (ct == n - 1)
break;
}
if (ct != n - 1)
sum = -1;
return sum;
}
int main()
{
int t;
cin >> t;
while (t--)
{
cin >> n >> m;
intt();
ans = 0;
for (int i = 0; i < m; i++)
{
p[i].IS = 0;
cin >> p[i].a >> p[i].b >> p[i].len;
}
sort(p, p + m, cmp);
for (int i = 0; i < m; i++)
{
if (find(p[i].a) != find(p[i].b))
{
pre[find(p[i].a)] = find(p[i].b);
ans += p[i].len; //ans记录最小生成树的值
p[i].IS = 1; //标记最小生成树所用到边
}
}
int flag = 0;
for (int i = 0; i < m; i++) //遍历最小生成树用到的每一条边
{
if (p[i].IS == 1) //选择最小生成树用到的一条边
num = i;
else
continue;
if (ans == kruskal(num)) //如果有满足条件的边num,则最小生成树不唯一
{
flag = 1;
break;
}
}
if (flag)
{
printf("Not Unique!\n");
}
else
{
printf("%d\n", ans);
}
}
return 0;
}