Problem 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!
题意:给一个无向图,判断这个图的最小生成树是否是唯一的。如果是唯一的,输出最小生成树的值,如果不是唯一的,输出“Not Unique!”
思路:
//如果已加入的点中存在着不止一个点到未加入的点
//有相同的距离,说明最小生成树不唯一
//比如A,B,C三个点AB=1,AC=2,BC=2
//prim已经加入了AB点,加入的点AB中有不止一个点到
//未加入的点C是同距离(AC=BC),说明最小生成树不唯一(AB,BC)(AB,AC)
#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
const int MAX = 105;
const int INF = 0x3f3f3f3f;
//最小生成树prim算法
struct A{
int arcs[MAX][MAX];//权值-->字符不同的个数
int arcnum; //边的数目
bool visit[MAX]; //顶点的访问情况
int vexnum; //顶点的数目
}G;
int d[MAX];//选中集与未选中集的距离
void prim(void){
int min,v,ans=0;
for(int i=1 ; i<=G.vexnum ; i++){
d[i] = G.arcs[1][i];
G.visit[i] = false;//每个点未访问
}
//起始点加入选中集
G.visit[1]=true;
for(int i=1 ; i<=G.vexnum-1 ; i++){//选n-1个顶点
//找出一个最短距离的点
min=INF;
for(int j=1 ; j<=G.vexnum ; j++){
if(!G.visit[j] && d[j]<min){
v=j;
min = d[j];
}
}
//已访问
G.visit[v]=true;
ans += min;
//只需要判断有没有相同最小边即可,有则不唯一
int k=0;
for(int j=1 ; j<G.vexnum ; j++){
//如果已加入的点中存在着不止一个点到未加入的点
//有相同的距离,说明最小生成树不唯一
//比如A,B,C三个点AB=1,AC=2,BC=2
//prim已经加入了AB点,加入的点AB中有不止一个点到
//未加入的点C是同距离(AC=BC),说明最小生成树不唯一(AB,BC)(AB,AC)
if(G.visit[j] && min==G.arcs[v][j]){
k++;
}
}
if(k != 1){
cout<<"Not Unique!"<<endl;
return;
}
//更新选中点集与未选中点集的距离
for(int j=1 ; j<=G.vexnum ; j++){
if(!G.visit[j] && G.arcs[v][j]<d[j]){
d[j]= G.arcs[v][j];
}
}
}
cout<<ans<<endl;
return;
}
int main(void){
int T;
cin>>T;
while(T--){
cin>>G.vexnum>>G.arcnum;
for(int i=1 ; i<=G.vexnum ; i++){
for(int j=1 ; j<=G.vexnum ; j++){
G.arcs[i][j] = (i==j)?0:INF;
}
}
//赋权值
for(int i=1 ; i<=G.arcnum ; i++){
int a,b,w;
cin>>a>>b>>w;
G.arcs[a][b] = G.arcs[b][a] = w;
}
prim();
}
return 0;
}