题目大意:给你一张图,问最小生成树是不是唯一的
解题思路:先将最小生成树求出来,并把形成最小生成树的边标记一下
接着在枚举那些不是最小生成树的边,看添加之后,形成的环中的最大边是否和该边相等,如果相等,则表示最小生成树不唯一
#include <cstdio>
#include <cstring>
#include <vector>
using namespace std;
#define N 110
#define M 10010
#define INF 0x3f3f3f3f
struct Node{
int x, y;
}node[M];
int dis[N][N], f[N], d[N], maxcost[N][N];
int n, m;
bool vis[N][N] ,mark[N];
vector<int> v;
void init() {
memset(dis, 0x3f, sizeof(dis));
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++)
dis[i][i] = 0;
int u, v, c;
for (int i = 0; i < m; i++) {
scanf("%d%d%d", &u, &v, &c);
node[i].x = u; node[i].y = v;
dis[u][v] = dis[v][u] = min(dis[u][v], c);
}
}
int Prim() {
for (int i = 1; i <= n; i++)
d[i] = INF;
memset(mark, 0, sizeof(mark));
memset(vis, 0, sizeof(vis));
v.clear();
d[1] = 0;
f[1] = 1;
int ans = 0;
for (int i = 1; i <= n; i++) {
int t = INF, x;
for (int j = 1; j <= n; j++)
if (d[j] < t && !mark[j])
t = d[x = j];
mark[x] = vis[f[x]][x] = vis[x][f[x]] = true;
ans += dis[f[x]][x];
int size = v.size();
for (int j = 0; j < size; j++)
maxcost[v[j]][x] = maxcost[x][v[j]] = max(maxcost[v[j]][f[x]], dis[f[x]][x]);
v.push_back(x);
for (int j = 1; j <= n; j++)
if (!mark[j] && dis[j][x] < d[j]) {
d[j] = dis[j][x];
f[j] = x;
}
}
return ans;
}
void solve() {
int ans = Prim();
bool flag = false;
int x, y;
for (int i = 0; i < m; i++) {
x = node[i].x; y = node[i].y;
if (!vis[x][y] && dis[x][y] == maxcost[x][y]) {
flag = true;
break;
}
}
if (flag)
printf("Not Unique!\n");
else
printf("%d\n", ans);
}
int main() {
int test;
scanf("%d", &test);
while (test--) {
init();
solve();
}
return 0;
}