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'.
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!
就是判读一下,改图的最小生成树是不是唯一
AC代码:
#include<iostream> #include<cstdio> #include<cstdlib> #include<cstring> #include<string> #include<queue> #include<algorithm> #include<map> #include<iomanip> #define maxn 101 using namespace std; int n,m; int f[maxn]; struct node { int x,y,w; }; node edge[maxn*maxn/2]; int cmp(node a, node b) { return a.w<b.w; } int getf(int i) { if(i==f[i]) return i; else { f[i]=getf(f[i]); return f[i]; } } int merge(int a, int b) { int u=getf(a); int v=getf(b); if(u==v) return 0; else { f[v]=u; return 1; } } int main() { int t,sum,cnt=0; scanf("%d",&t); while(t--) { int i; sum=0,cnt=0; scanf("%d%d",&n,&m); for(i=1;i<=n;++i) f[i]=i; for(i=0;i<m;++i) scanf("%d%d%d",&edge[i].x,&edge[i].y,&edge[i].w); sort(edge,edge+m,cmp); for(i=0;i<m;++i) { //先构造出最小生成树 if(cnt>=n-1) break; if(merge(edge[i].x,edge[i].y)) { cnt++; sum+=edge[i].w; } } int flag=0; for(int j=i;j<m;++j) { //看一下剩下的边中有没有跟前面构造的最小生成树的最大的边相等的变 if(edge[j].w==edge[i-1].w) { // 存在的话,去掉最小生成树的最大边,还上改边看看能不能构成联通 f[edge[i-1].y]=edge[i-1].y;//图,可以的话,则最小生成树不唯一 if(merge(edge[j].x,edge[j].y)) { flag=1;//一旦存在另一个最小生生成树,则跳出循环,打印出Not Unique! break; } } else break;// 知道遍历到边不等于前面构造的最小生成树的最大边,则跳出循环 } if(flag) printf("Not Unique!\n"); else printf("%d\n",sum); } return 0; }