次小生成树。。。。。
思路就是枚举删掉最小生成树里的每条边,再求一次看权值和是否相同。
因为ok数组开小WA了一下午。。。我还是太弱。。。
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
#define CLS(x, y) memset(x, y, sizeof(x))
inline int read()
{
int x = 0; int v = 1, c;
while(c = getchar(), c < '0' || c > '9') if(c == '-') v = -1;
for(; c >= '0' && c <= '9'; c = getchar()) x = x * 10 + c - '0';
return x * v;
}
template<typename T> inline bool relax(T &x, T y) { return x > y ? x = y, 1 : 0; }
template<typename T> inline bool tense(T &x, T y) { return x < y ? x = y, 1 : 0; }
const int MAXN = 105;
const int MAXM = 10005;
struct DSU
{
int fa[MAXN];
inline void init(int n) {
for(int i = 1; i <= n; ++i) fa[i] = i;
}
int getfa(int x) {
return fa[x] == x ? x : fa[x] = getfa(fa[x]);
}
};
struct Edge
{
int u, v, w;
bool book;
Edge(int u = 0, int v = 0, int w = 0, bool bk = 0): u(u), v(v), w(w), book(bk) {}
bool operator < (const Edge &b) const {
return w < b.w;
}
};
struct Graph
{
int n, m;
int head[MAXN];
int next[MAXM];
Edge edge[MAXM];
bool ok[MAXM];
DSU dsu;
void init(int n) {
this->n = n; m = 0; CLS(head, -1); CLS(ok, 0);
}
inline int kruskal(bool first)
{
dsu.init(n);
int res = 0, cnt = 0;
for(int i = 0; cnt < n - 1 && i < m; ++i)
{
if(edge[i].book) continue;
int a = dsu.getfa(edge[i].u);
int b = dsu.getfa(edge[i].v);
if(a == b) continue;
dsu.fa[b] = a;
cnt++; if(first) ok[i] = 1;
res += edge[i].w;
}
if(cnt < n - 1) return -1;
return res;
}
}g;
int n, m;
void input()
{
n = read(); m = read(); g.init(n); g.m = m;
for(int i = 0; i < m; ++i)
{
int a = read(), b = read(), c = read();
g.edge[i] = Edge(a, b, c);
}
sort(g.edge, g.edge + m);
}
void solve()
{
int ans = g.kruskal(1);
if(ans == -1) { puts("Not Unique!"); return; }
for(int i = 0; i < m; ++i)
{
if(!g.ok[i]) continue;
g.edge[i].book = 1;
int res = g.kruskal(0);
g.edge[i].book = 0;
if(res == ans) { puts("Not Unique!"); return; }
}
printf("%d\n", ans);
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
int test = read();
while(test--)
{
input();
solve();
}
#ifndef ONLINE_JUDGE
fclose(stdin), fclose(stdout);
#endif
return 0;
}