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!
题意分析:mst唯一的标准是看最小生成树中是否含有权值相等的两个边,如果有就不唯一,否则就唯一。
解题思路:就是prime的模型,只需要在每次找到一条路后判断以前走过的路的权值有没有跟这条边的权值相等的就可以了。
下面上代码
#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;
int e[200][200],dis[200],book[200];
int inf=99999999;
int main()
{
int sum,i,j,k,min,n,t1,t2,t3,m,v,flag,t,u,l,s;
cin>>t;
while(t--)
{
cin>>n>>m;
sum=flag=0;
memset(book,0,sizeof(book));
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if(i==j) e[i][j]=0;
else e[i][j]=inf;
for(i=1;i<=m;i++)
{
cin>>t1>>t2>>t3;
if(t3<e[t1][t2])
e[t1][t2]=e[t2][t1]=t3;
}
for(i=1;i<=n;i++)
dis[i]=e[1][i];
book[1]=1;
for(i=1;i<n;i++)
{
min=inf;
for(j=1;j<=n;j++)
{
if(book[j]==0&&dis[j]<min)
{
min=dis[j];
u=j;
}
}
s=0;//因为会找到自身的边,所以在此处置零。
for(l=1;l<=n;l++)
if(book[l]!=0&&e[l][u]==min)
s++;
//循环每次是从1开始的因此会找到它本身这条边,因此判断要大于1
if(s>1)
{
flag=1;
break;
}
book[u]=1;
sum+=dis[u];
for(v=1;v<=n;v++)
if(book[v]==0&&dis[v]>e[u][v])
dis[v]=e[v][u];
}
if(flag==0)
cout<<sum<<endl;
else
cout<<"Not Unique!"<<endl;
}
return 0;
}