The Unique MST
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 35999 | Accepted: 13145 |
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!
C/C++:
#include <map>
#include <queue>
#include <cmath>
#include <vector>
#include <string>
#include <cstdio>
#include <cstring>
#include <climits>
#include <iostream>
#include <algorithm>
#define INF 0x3f3f3f3f
using namespace std;
const int my_max_edge = , my_max_node = ; int t, n, m, my_book_edge[my_max_edge], my_pre[my_max_node], my_first; struct edge
{
int a, b, val;
}P[my_max_edge]; bool cmp(edge a, edge b)
{
return a.val < b.val;
} int my_find(int x)
{
int n = x;
while (n != my_pre[n])
n = my_pre[n];
int i = x, j;
while (n != my_pre[i])
{
j = my_pre[i];
my_pre[i] = n;
i = j;
}
return n;
} int my_kruskal(int my_flag)
{
int my_ans = ;
for (int i = ; i <= n; ++ i)
my_pre[i] = i; for (int i = ; i < m; ++ i)
{
int n1 = my_find(P[i].a), n2 = my_find(P[i].b);
if (n1 == n2 || my_flag == i) continue;
my_pre[n1] = n2;
if (my_first)my_book_edge[i] = ;
my_ans += P[i].val;
} int temp = my_find();
for (int i = ; i <= n; ++ i)
if (temp != my_find(i))
return -;
return my_ans;
} int main()
{
scanf("%d", &t);
while (t --)
{
scanf("%d%d", &n, &m);
for (int i = ; i < m; ++ i)
scanf("%d%d%d", &P[i].a, &P[i].b, &P[i].val);
sort(P, P + m, cmp);
memset(my_book_edge, , sizeof(my_book_edge)); my_first = ;
int mst = my_kruskal(-), flag = ;
if (mst == -)
{
printf("0\n");
continue;
}
my_first = ;
for (int i = ; i < m; ++ i)
{
if (my_book_edge[i])
{
if (mst == my_kruskal(i))
{
printf("Not Unique!\n");
flag = ;
break;
}
}
}
if (flag) printf("%d\n", mst);
}
return ;
}