一、内容

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!

二、思路

  • 求最小生成树是否唯一。 可以求非严格次小生成树看是否和最小生成树相等,如果不相等那么就唯一。但是不必那么麻烦。从prime的思路出发,每次选取一个点(到集合的距离最短), 若这个点到这个集合的最短距离有2条以上的边,那么代表这个生成树不唯一。 如果都只有1一条边那么代表唯一。
  • POJ 1679   The Unique MST_i++

三、代码

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 105;
int t, n, m, u, v, w, g[N][N], d[N], cnt[N]; //cnt判断加入集合中的边有多少条 
bool vis[N];
int prime() {
	int ans = 0;
	memset(d, 0x3f, sizeof(d));
	memset(vis, false, sizeof(vis));
	memset(cnt, 0, sizeof(cnt));
	for (int i = 0; i < n; i++) {
		int t = -1;
		for (int j = 1; j <= n; j++) {
			if (!vis[j] && (t == -1 || d[t] > d[j])) t = j;
		}
		vis[t] = true;
		if (i) ans += d[t];
		for (int j = 1; j <= n; j++) {
			if (t == j) continue;
			if (d[j] == g[t][j]) cnt[j]++; //代表相同的边有几条 
			if (d[j] > g[t][j]) d[j] = g[t][j], cnt[j] = 1; 
		}
	}
	return ans;
}
int main() {
	scanf("%d", &t);
	while (t--) {
		scanf("%d%d", &n, &m);
		memset(g, 0x3f, sizeof(g));
		for (int i = 1; i <= m; i++) {
			scanf("%d%d%d", &u, &v, &w);
			g[u][v] = g[v][u] = min(g[v][u], w);
		}
		int ans = prime();
		bool ok = true;
		for (int i = 1; i <= n; i++) {
			if (cnt[i] > 1) {
				ok = false;
				break;
			}
		}
		if (ok) printf("%d\n", ans);
		else printf("Not Unique!\n"); 
	}
	return 0;
}