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!
prim算法判断最小生成树是否唯一:如果已经加入生成树的点中有两个或者以上的点,到即将加入生成树的点的最小权值相等,则生成树不唯一。
#include<stdio.h>
int main()
{
int t, i, j;
int dis[200];
int map[105][105];
int n, m,a,b,c;
int min;
scanf("%d", &t);
while (t--)
{
int count=0, sum = 0, f=0;
int book[200] = { 0 };
scanf("%d%d", &n, &m);
for (i = 1; i <= n; i++)
{
for (j = 1; j <= n; j++)
{
if (i == j)
map[i][j] = 0;
else
map[i][j] = 9999999;
}
}
for(i=1; i<=m; i++)
{
scanf("%d%d%d",&a, &b, &c);
map[a][b] = map[b][a] = c;
}
for (i = 1; i <= n; i++)
dis[i] = map[1][i];
count++;
book[1] = 1;
while (count < n)
{
min = 9999999;
for (i = 1; i <= n; i++)
{
if (book[i] == 0 && dis[i] < min)
{
min = dis[i];
j = i;
}
}
int s = 0;
for (i = 1; i <= n; i++)
if (book[i] == 1 && min == map[i][j])//如果已经加入生成树的点中,到即将加入生成树的点的最小权值相等
s++;
if (s > 1)//当有两个或者以上的时候
{
f = 1;
break;
}
count++, sum += dis[j], book[j]=1;
int k;
for (k = 1; k <= n; k++)
{
if (book[k] == 0 && dis[k] > map[j][k])
dis[k] = map[j][k];
}
}
if (f == 1)
printf("Not Unique!n");
else
printf("%dn", sum);
}
}
最后
以上就是感性黑裤最近收集整理的关于The Unique MST(判断最小生成树是否唯一)C语言的全部内容,更多相关The内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复