记录结果边集 每次删除一个再进行 最小树操作
#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<algorithm>
using namespace std;
const int maxn = 107;
int pre[maxn];//并查集的父节点数组
int Rank[maxn];//通过秩合并的数组
int n, m;
int t;
typedef struct node
{
int s, e, w;
}node;
int edgeans[maxn*maxn];
node Edge[maxn*maxn];
bool cmp(const node& a, const node& b)
{
return a.w < b.w;
}
void init()
{
for (int i = 0; i < maxn; i++)
{
pre[i] = i;
Rank[i] = 0;
}
}
int find(int x)//在找到x的根的同时,实现对于并查集搜索树的合并
{
int root = x;
while (root != pre[root])
{
root = pre[root];
}
while (x != pre[x])
{
int t = pre[x];
pre[x] = root;
x = t;
}
return root;
}
void unitset(int root0, int root1)//实现按照秩相加
{
if (Rank[root0] < Rank[root1])
{
pre[root0] = root1;
}
else
{
pre[root1] = root0;
if (Rank[root0] == Rank[root1]) Rank[root0]++;
}
}
bool Kruskal(int &ans,int mark)
{
ans = 0;
int amount = 0;
for (int i = 0; i < m; i++)
{
if (i == mark)
continue;
int root0 = find(Edge[i].s);
int root1 = find(Edge[i].e);
if (root0 != root1)
{
unitset(root0, root1);
ans += Edge[i].w;
if (mark == -1)
{
edgeans[amount] = i;
}
amount++;
}
}
if (amount != n - 1)
return 0;
return 1;
}
int main()
{
cin >> t;
while (t--)
{
init();
cin >> n >> m;
for (int i = 0; i < m; i++)
{
cin >> Edge[i].s >> Edge[i].e >> Edge[i].w;
Edge[i].s--;
Edge[i].e--;
//Edge[i].vis = 0;
}
sort(Edge, Edge + m, cmp);
int ans = 0;
Kruskal(ans,-1);
int ansall = ans;
bool flag = 0;
for (int i = 0;i < n - 1;i++)
{
init();
ans = 0;
if (Kruskal(ans, edgeans[i]) && ans == ansall)
{
flag = 1;
break;
}
}
if (flag)
cout << "Not Unique!" << endl;
else
cout << ansall << endl;
}
return 0;
}