最小生成树是否唯一,再找到的最小生成树中每次删掉一条边,再找
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int m, n;
structedge
{
intx, y;
intflag;
intw;
} node[10000];
int parent[101];
charused[10000];
int cmp(const void *a, constvoid *b)
{
edge *x, *y;
x = (edge *)a;
y = (edge *)b;
returnx->w - y->w;
}
int find(int x)
{
if(x == parent[x])
returnx;
else
returnparent[x] = find(parent[x]);
}
int Kruskal(int first)
{
inti, result = 0;
for(i=0; i<m; i++)
{
if(node[i].flag)
{
inta = find(node[i].x);
intb = find(node[i].y);
if(a != b)
{
result += node[i].w;
parent[a] = b;
if(first)
{
used[i] = 1;
// printf("%d %d [%d][%d]n", a, b, node[i].w, i);
}
}
}
}
inta = find(1);
for(i=1; i<=n; i++)
if(find(i) != a)
return-1;
returnresult;
}
int main ()
{
intt;
inti, j, k;
intresult;
scanf("%d", &t);
while(t--)
{
scanf("%d%d", &n, &m);
for(i=0; i<m; i++)
{
scanf("%d%d%d", &node[i].x, &node[i].y, &node[i].w);
node[i].flag = 1;
}
memset(used, 0,sizeof(used));
qsort(node, m,sizeof(node[0]), cmp);
for(i=1; i<=n; i++)
parent[i] = i;
result = Kruskal(1);
//for(i=1; i<=n; i++)
// printf("%d ", parent[i]);
// printf("n");
intmin = 0xfffffff;
for(i=0; i<m; i++)
{
if(used[i])
{
for(j=1; j<=n; j++)
parent[j] = j;
node[i].flag = 0;
intx = Kruskal(0);
if(x!= -1 && x < min)
min = x;
node[i].flag = 1;
}
}
if(result == min)
printf("Not Unique!n");
else
printf("%dn", result);
}
return0;
}