クルーズカール(Kruskal)アルゴリズムは最小の生成木を求めます


/*
 *Kruskal   MST 
*/
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <string>
#include <algorithm>
#include <queue>
#include <set>
#include <stack>
using namespace std;


const int MAXN = 110;					//     
const int MAXM = 10000;					//     
int F[MAXN];							//      

struct Edge {
	int u, v, w;
}edge[MAXM];						//      ,    /  /   

int tol = 0;		//     

void addedge(int u, int v, int w) {
	edge[tol].u = u;
	edge[tol].v = v;
	edge[tol++].w = w;
}

bool cmp(Edge a, Edge b) {			//    ,             
	return a.w < b.w;
}

int find(int x) {
	if (F[x] == -1) 
		return x;
	else
		return F[x] = find(F[x]);
}

int Kruskal(int n) {		//    ,          ,       -1 
	memset(F, -1, sizeof(F));
	sort(edge, edge+tol, cmp);
	int cnt = 0;			//        
	int ans = 0;
	for (int i = 0; i<tol; i++) {
		int u = edge[i].u;
		int v = edge[i].v;
		int w = edge[i].w;
		int t1 = find(u);
		int t2 = find(v);
		if (t1 != t2) {
			ans += w;
			F[t1] = t2;
			cnt ++ ;
		}
		if (cnt == n-1)
			break;
	}
	if (cnt < n-1)
		return -1;
	else 
		return ans;
}

int main() {
	int t;
	cin >> t;
	while (t --) {
		tol = 0;
		memset(edge, 0, sizeof(edge));
		int n, m;
		cin >> n >> m;
		while (m --) {
			int x, y, w;
			cin >> x >> y>> w;
			addedge(x, y, w);
		}
		int res = Kruskal(tol);
		if (res == -1)
			cout << "Not Unique!"<< endl;
		else
			cout << res << endl;
	
	}
	return 0;
}