题目链接
思想:Kruskal算法思想:把所有的边升序排序,每次加一条边,加的时候判断一下当前边所连接的两个顶点是否已经连通(并查集),是则舍弃,否则 要这条边并且更新一下并查集的head数组。
如果最小生成树不唯一,那么权值相同的边肯定有多条。
每次在加边的时候,判断和在整个图中和这条边权值相等且能加入到最小生成树的边有几条(设为sum1)(每次判断不更新并查集head数组),然后将这些权值相等的边依次加入到树中(更新head数组),如果此时能加入的边(sum2),有sum1>sum2,说明最小生成树不唯一。
# include <iostream>
# include <algorithm>
# include <stdio.h>
# include <string.h>
using namespace std;
# define MAX 0x3f3f3f3f
# define MAXN 110
# define MAXM 11000
int N, M;
int head[MAXN];///并查集记录父节点数组
int ans;
struct node
{
int s, e;
int price;
} z[MAXM];///存边
bool cmp(struct node A, struct node B)
{
return A.price<B.price;
}
void Init()
{
for(int i=1; i<=100; i++)
head[i]=i;
ans=0;
}
int Find(int a)
{
int i;
for(i=head[a]; i!=head[i]; i=head[i]);
return i;
}
bool Kruskal()
{
sort(z,z+M,cmp);
int j;
for(int i=0; i<M; i=j)
{
int sum1=0, sum2=0;
j=i;
while(z[j].price==z[i].price&&j<M)
{
int a=Find(z[j].s);
int b=Find(z[j].e);
if(a!=b)
sum1++;
j++;
}
j=i;
while(z[j].price==z[i].price&&j<M)
{
int a=Find(z[j].s);
int b=Find(z[j].e);
if(a!=b)
{
head[a]=b;
sum2++;
ans+=z[i].price;
}
j++;
}
if(sum1>sum2)
return false;
}
return true;
}
int main()
{
int T;
while(cin>>T)
{
while(T--)
{
cin>>N>>M;
Init();
for(int i=0; i<M; i++)
{
int a, b, c;
cin>>a>>b>>c;
z[i]=(node)
{
a,b,c
};
}
int flag=Kruskal();
if(!flag)
cout<<"Not Unique!"<<endl;
else
cout<<ans<<endl;
}
}
return 0;
}