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:
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!
题目大意 : 给出数据组数 t , 一个有 n 个顶点和 m 条边的图和每条边的权值,两个点之间最多只有一条边相连,判断最小生成树是否唯一,若唯一,则输出最小生成树的权值和,否则输出 Not Unique!
solution
也是和prim模板题差不多的,就是每在找到一个新的点之后,判断一下还有没有minn[]值和这个点一样的点,有的话那么当然不是唯一的,直接输出没有就好;还有一个判断是看找到一个点后,用这个点更新minn[]值时,是否有原来minn[]值等于用新点更新的minn[]值的点,如果有,则说明那个店可以通过另一条路到达,所以输出没有
Code
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#define INF 0x7fffffff
using namespace std;
int map[105][105],minn[105];
int m,n;
bool visit[105];
int Prim ()
{
int i,j,k;
int temp,ans=0;
minn[1]=0;
for (i=1;i<=n;i++)
minn[i]=map[1][i];
visit[1]=true;
for (i=1;i<n;i++)
{
// k=0;
for (temp=INF,j=1;j<=n;j++)
if (minn[j]<temp&&!visit[j])
k=j,temp=minn[k];
ans+=temp;
visit[k]=true;
for (j=1;j<=n;j++)
if (!visit[j]&&minn[j]==temp)
return -1;
for (j=1;j<=n;j++)
if (!visit[j])
{
if (minn[j]>map[k][j])
minn[j]=map[k][j];
else if (minn[j]==map[k][j]&&minn[j]!=INF)
return -1;
}
}
return ans;
}
void init ()
{
int i;
for (i=1;i<=n;i++)
for (int j=1;j<=n;j++)
map[i][j]=INF;
for (i=1;i<=n;i++)
map[i][i]=0;
memset(visit,false,sizeof(visit));
}
int main ()
{
int T;
scanf("%d",&T);
while (T--)
{
int x,y,w;
scanf("%d%d",&n,&m);
init ();
for (int i=0;i<m;i++)
{
scanf("%d%d%d",&x,&y,&w);
map[x][y]=w;
map[y][x]=w;
}
int ans=Prim();
if (ans == -1)
printf("Not Unique!\n");
else
printf("%d\n",ans);
}
return 0;
}
Solution描述得似乎不很好