The Unique MST
Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 42304 Accepted: 15424
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:
- V’ = V.
- 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!
题意很明确,上代码:
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
using namespace std;
const int N=(int)1e7;
struct node
{ //eq 标记是否value相同 简化过程,如果一条边没有相同的,那么这条边不能被替换
int u,v,w; //used 标记是否被用过 只是在第一次MST的时候有用
int eq,used,del; //del 在判断生成MST是否为使用的标记
}e[N];
int n,first,m;
int pre[N];
bool cmp(node a,node b) //排序 value
{
return a.w<b.w;
}
int find(int x) //找父节点并压缩路径
{
if(x!=pre[x])
pre[x]=find(pre[x]);
return pre[x];
}
int kruskal() //kruskal算法
{
int i,f1,f2,ans,cnt;
ans=cnt=0;
for(i=1;i<=n;i++)
pre[i]=i;
for(i=0;i<m;i++)
{
if(e[i].del) //这就是此次查重过程中要跳过的边
continue;
f1=find(e[i].u);
f2=find(e[i].v);
if(f1!=f2)
{
if(first)
e[i].used=1;
pre[f1]=f2;
ans+=e[i].w;
cnt++;
if(cnt>=n-1)
break;
}
}
return ans;
}
int main()
{
int i,j,T;
cin>>T;
while(T--)
{
cin>>n>>m;
for(i=0;i<m;i++)
{
cin>>e[i].u>>e[i].v>>e[i].w;
e[i].del=e[i].eq=e[i].used=0;
}
sort(e,e+m,cmp);
for(i=0;i<m;i++) //来便利每个边的value是否重样的
{
for(j=i+1;j<m;j++) //是从第一个开始遍历的,看是否有与一重复的
{ //然后 从第二个开始遍历,看是否有与二重复的
if(e[i].w==e[j].w) //以此类推就行了
e[i].eq=e[j].eq=1;
else
break;
}
}
first=1;
int ans=kruskal();
first=0;
for(i=0;i<m;i++)
{
//if(e[i].used) 如果去掉重边的限制,如果这条边被用过并且还唯一的话,也把他删了的话,结果只有两种生成比它还大的树,或者构不成树
if(e[i].used&&e[i].eq) //如果在 *第一次* 被用过并且重复
{ //就标记成 1 ,那么在MST(最小生成树)生成中,此边就会被跳过
e[i].del=1; //但是只是重复的边而没有用过
if(kruskal()==ans) //则不会被进行MST查唯一过程
break; //这样就确定了每次的MST都不会和前面的MST一样
e[i].del=0; //每次生成完了之后就把这条边恢复
} //以方便下一次MST把这条边合并进去
} //这里再提一下,每次MST跳过的边都是用过的并且重复的
if(i<m) //只用过了或者只标记重复了是不会被跳过的
cout<<"Not Unique!"<<endl;
else
cout<<ans<<endl;
}
return 0;
}