poj 1679 The Unique MST

it2024-04-14  14

The Unique MST Time Limit: 1000MS Memory Limit: 10000KTotal Submissions: 13474 Accepted: 4674

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! #include<iostream> #include<algorithm> using namespace std; const int MAX = 110; struct node { int x; int y; int weight; }E[MAX*MAX]; int father[MAX]; int indexEdge[MAX]; int index; int n, m; bool cmp(node a, node b) { return a.weight < b.weight; } int find(int x) { if(father[x] != x) { father[x] = find(father[x]); } return father[x]; } void union_set(int a, int b) { father[a] = b; } void union_make() { for(int k = 1; k <= n; k ++) father[k] = k; } int Kruskal(int location) { int ans = 0; int tx, ty; int cnt = 0; if (location == -1) index = 0; union_make(); for(int i = 0; i < m; i ++) { if(i == location) continue; tx = find(E[i].x); ty = find(E[i].y); if(tx != ty) { union_set(tx, ty); ans += E[i].weight; cnt ++; if(location == -1) { indexEdge[index] = i; index ++; } if(cnt == n - 1) break; } } if(cnt == n - 1) return ans; return -1; } int main() { int t, i; freopen("e:\\data.txt", "r", stdin); freopen("e:\\out.txt", "w", stdout); cin>>t; while(t--) { memset(E, 0, sizeof E); memset(indexEdge, 0, sizeof(indexEdge)); cin>>n>>m; for(i = 0; i < m; i ++) cin>>E[i].x>>E[i].y>>E[i].weight; sort(E, E + m, cmp); int min = Kruskal(-1); int temp; for(i = 0; i < index; i ++) { temp = Kruskal(indexEdge[i]); if(temp == min) { cout<<"Not Unique!"<<endl; break; } } if(i == index) cout<<min<<endl; } return 0; }

 

要求最小生成树是否是唯一首先求次最优的最小生成树,如果次最小生成树的总长度和最小生成树的总长度相同,则说明非唯一

求次最小生成树的方法:

在求最小生成树时先把用到的边都记录下来,

然后枚举每一条记录中的边,将该条边去掉,在剩下的边中求最小生成树,结果就是次最小生成树

 

转载于:https://www.cnblogs.com/w0w0/archive/2012/05/09/2491881.html

相关资源:数据结构—成绩单生成器
最新回复(0)