题意描述:
给出数据之间的节点信息,把他们连接起来但是要距离之和最短,要是一各样例有多种建立的方法就输出Not Unique!;
解题思路:
用最小生成树的普里姆算法找到最短边后对其进行标记去寻找已经标记(以前找过这一条边)的点他到当前标记的点的距离等于min(等于最小距离)的顶点一共有几个要是有多于一个点的话,就说明这个图表的建法不只有一种下面来举个例子:
4
1 2 2
1 3 2
2 3 2
3 4 2
1 4 2
最开始由于2距离1比较近(虽然他们都相等),找到他之后就没有在更新,所以节点1和节点2现在都已经被标记,然后找到了节点3,这时候就出现了刚才说的问题,通过以 2为中心节点找到3但是当前1和2都被标记,而且两者到3的距离都是3,那就到底建立2和3这条路线还是1和3这一条路线,很明显这两种都可以,所以这就是出现了多种建树的方法,需要修改的地方就是
for(int v=1; v<=n; v++)
{
if(book[v]!=0&&min==e[v][u])
k++;
}
if(k>1)//修改地方做一个标记
{
p=0;
printf("Not Unique!\n");
break;
}
原文题目:
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:
- V’ = V.
- 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!
AC代码:
#include<stdio.h>
#include<string.h>
int e[2000][2000];
int dis[20000],book[20000];
int inf=99999999;
int main()
{
int n,m,i,j,k,t,sum,u,t1,t2,t3,min,p;
scanf("%d", &t);
while(t--)
{
scanf("%d %d", &n,&m);
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++)
{
scanf("%d %d %d", &t1,&t2,&t3);
if(e[t2][t1]>t3)
{
e[t2][t1]=e[t1][t2]=t3;
}
}
for(i=1; i<=n; i++)
dis[i]=e[1][i];
book[1]=1; sum=0; p=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;
}
}
int k=0;
for(int v=1; v<=n; v++)
{
if(book[v]!=0&&min==e[v][u])
k++;
}
if(k>1)
{
p=0;
printf("Not Unique!\n");
break;
}
book[u]=1;
sum+=dis[u];
for(k=1; k<=n; k++)
{
if(book[k]==0&&dis[k]>e[u][k])
dis[k]=e[u][k];
}
}
if(p)
printf("%d\n", sum);
}
return 0;
}