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!’.
#include<iostream> #include<cstdio> #include<queue> #include<map> #include<cmath> #include<algorithm> #include<cstring> usingnamespacestd; constint N = 110, M = 1e5 + 10; constint inf = 0x3f3f3f3f; int n, m;
voidinit(){ for(int i = 0; i <= N; ++i) { fa[i] = i; } }
int mst[M]; // 最小生成树所有边的下标 int mst_size; // 最小生成树的边权和
intkruskal(){ init(); int flag = 0; int ans = 0; mst_size = 0; sort(edge + 1, edge + 1 + m, cmp); for(int i = 1; i <= m; ++i) { int x = get(edge[i].x); int y = get(edge[i].y); if(x != y) { ans += edge[i].z; fa[x] = y; mst[++mst_size] = i; } } return ans; }
// 次小生成树 intsec_mst(){ int ans = inf; for(int i = 1; i <= mst_size; ++i) { init(); int sum = 0; int cnt = 0; for(int j = 1; j <= m; ++j) { if(j != mst[i]) { // 删去最小生成树中的一条边 int x = get(edge[j].x); int y = get(edge[j].y); if(x != y) { sum += edge[j].z; fa[x] = y; ++cnt; } } } if(cnt != mst_size) continue; ans = min(ans, sum); } if(ans == inf) return-1; return ans; }
intmain(){ int T; scanf("%d", &T); while(T--) { scanf("%d%d", &n, &m); for(int i = 1; i <= m; ++i) { scanf("%d%d%d", &edge[i].x, &edge[i].y, &edge[i].z); } int tmp1 = kruskal(); int tmp2 = sec_mst(); if(tmp1 == tmp2) { printf("Not Unique!\n"); } else { printf("%d\n", tmp1); } } return0; }