概述
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 2Sample Output
3 Not Unique!
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
using namespace std;
const int N=10010;
int pre[N];int n,m,a,b,x1,x2,x;
struct ch
{
int a,b,x;
}sh[N];
bool cmp(ch a,ch b)
{
return a.x<b.x;
}
int find(int x){
if(pre[x]!=x)
pre[x]=find(pre[x]);
return pre[x];
}
int merge(int a,int b){
int x1=find(a);
int x2=find(b);
if(x1!=x2)
{
pre[x1]=x2;
return 1;
}
return 0;
}
int main()
{
int t;cin>>t;
while(t--)
{
int d[N];memset(d,0,sizeof(d));int cou=0;
cin>>n>>m;
for(int i=1;i<=m;i++)
{
cin>>sh[i].a>>sh[i].b>>sh[i].x;
}
int ans=0;
for(int i=1;i<=n;i++)pre[i]=i;
sort(sh+1,sh+m+1,cmp);
for(int i=1;i<=m;i++)
{
if(merge(sh[i].a,sh[i].b))
{
ans+=sh[i].x;
d[cou++]=i;
}
}
int f=0;
for(int i=1;i<cou;i++)//1
<cou
{
for(int j=1;j<=n;j++)pre[j]=j;
int res=0;int cou2=0;//2
for(int j=1;j<=m;j++)
{
if(d[i]==j)continue;
if(merge(sh[j].a,sh[j].b)){
res+=sh[j].x;
cou2++; // 3
}
}
if(res==ans&&cou2==n-1)
{
f=1;
break;
}
if(f==1)break;
}
if(f==1)printf("Not Unique!n");
else
printf("%dn",ans);
}
return 0;
}
最后
以上就是霸气大门为你收集整理的The Unique MST(最小生成树)的全部内容,希望文章能够帮你解决The Unique MST(最小生成树)所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复