POJ 1679 The Unique MST(判断最小生成树是否唯一)

时间:2023-03-09 08:14:12
POJ 1679 The Unique MST(判断最小生成树是否唯一)

题目链接:

http://poj.org/problem?id=1679

Description

Given a connected undirected graph, tell if its minimum spanning tree is unique.

Definition 1 (Spanning Tree): Consider a connected, undirected graph
G = (V, E). A spanning tree of G is a subgraph of G, say T = (V', E'),
with the following properties:

1. V' = V.

2. T is connected and acyclic.

Definition 2 (Minimum Spanning Tree): Consider an edge-weighted,
connected, undirected graph G = (V, E). The minimum spanning tree T =
(V, E') of G is the spanning tree that has the smallest total cost. The
total cost of T means the sum of the weights on all the edges in E'.

Input

The
first line contains a single integer t (1 <= t <= 20), the number
of test cases. Each case represents a graph. It begins with a line
containing two integers n and m (1 <= n <= 100), the number of
nodes and edges. Each of the following m lines contains a triple (xi,
yi, wi), indicating that xi and yi are connected by an edge with weight =
wi. For any two nodes, there is at most one edge connecting them.

Output

For each input, if the MST is unique, print the total cost of it, or otherwise print the string 'Not Unique!'.

Sample Input

2
3 3
1 2 1
2 3 2
3 1 3
4 4
1 2 2
2 3 2
3 4 2
4 1 2

Sample Output

3
Not Unique!

Source

 /*
问题
判断最小生成树是否唯一 解题思路
利用克鲁斯卡尔算法计算出最小花费和标记每一条边,每次删除一条标记边,再进行一次克鲁斯卡尔,如果能够生成最小生
成树而且最小代价相同,说明最小生成树不唯一,否则说明最小生成树是唯一的输出最小花费。
*/
#include<cstdio>
#include<algorithm> using namespace std; struct EDGE{
int u,v,w,f;
}edge[];
int n,m;
int fa[];
int cmp(struct EDGE a,struct EDGE b){
return a.w<b.w;
}
int kruskal1();
int kruskal2();
int merge(int u,int v);
int getf(int v);
int ok(int ans); int main()
{
int T,i;
scanf("%d",&T); while(T--){
scanf("%d%d",&n,&m);
for(i=;i<m;i++){
scanf("%d%d%d",&edge[i].u,&edge[i].v,&edge[i].w);
edge[i].f=;
} sort(edge,edge+m,cmp);
/*for(i=0;i<m;i++){
printf("%d %d %d %d\n",edge[i].u,edge[i].v,edge[i].w,edge[i].f);
}*/ int mina=kruskal1();
//printf("%d\n",mina); if(ok(mina))
printf("%d\n",mina);
else
printf("Not Unique!\n");
}
return ;
} int ok(int ans){
int temp,i;
for(i=;i<m;i++){
if(edge[i].f){
//printf("删去 %d 这条边\n",i);
edge[i].f=-;
temp=kruskal2();
if(temp == ans)//构成最小生成树并且最小代价相同
return ; edge[i].f=;
}
}
return ;
} int kruskal1()
{
int i;
for(i=;i<=n;i++)
fa[i]=i;
int c=,sum=; for(i=;i<m;i++){
if(merge(edge[i].u,edge[i].v)){
c++;
sum += edge[i].w;
edge[i].f=;
}
if(c == n-)
break;
}
return sum;
} int kruskal2()
{
int i;
for(i=;i<=n;i++)
fa[i]=i;
int c=,sum=; for(i=;i<m;i++){
if(edge[i].f >= && merge(edge[i].u,edge[i].v)){
//printf("使用 %d 这条边 %d %d %d\n",i,edge[i].u,edge[i].v,edge[i].w);
c++;
sum += edge[i].w;
}
if(c == n-)
break;
} if(c == n-)
return sum;
else
return -;
} int merge(int u,int v){
int t1=getf(u);
int t2=getf(v);
if(t1 != t2){
fa[t2]=t1;
return ;
}
return ;
} int getf(int v){
return fa[v] == v ? v : fa[v]=getf(fa[v]);
}