POJ 1679The Unique MST

来源:互联网 发布:软件产品质量承诺 编辑:程序博客网 时间:2024/06/10 00:17
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
23 31 2 12 3 23 1 34 41 2 22 3 23 4 24 1 2
Sample Output
3

Not Unique!

可以参考fzu2087,求出几条边在最小生成树上,超过n-1,那最小生成树肯定不唯一。

#include<cmath>  #include<queue>  #include<cstdio>  #include<cstring>  #include<algorithm>  using namespace std;#define ms(x,y) memset(x,y,sizeof(x))  #define rep(i,j,k) for(int i=j;i<=k;i++)  #define loop(i,j,k) for (int i=j;i!=-1;i=k[i])  #define inone(x) scanf("%d",&x)  #define intwo(x,y) scanf("%d%d",&x,&y)  #define inthr(x,y,z) scanf("%d%d%d",&x,&y,&z)  #define lson x<<1,l,mid  #define rson x<<1|1,mid+1,r  const int N = 1e5 + 10;const int INF = 0x7FFFFFFF;int T, n, m, ans;int x[N], y[N], z[N], a[N], fa[N];int get(int x) { return x == fa[x] ? x : fa[x] = get(fa[x]); }bool cmp(int u, int v) { return z[u] < z[v]; }int main(){inone(T);while (T--){intwo(n, m);rep(i, 1, m) inthr(x[i], y[i], z[i]), a[i] = i;sort(a + 1, a + m + 1, cmp);rep(i, 1, n) fa[i] = i;int cnt = ans = 0;for (int i = 1, j; i <= m; i = j){for (j = i; j <= m&&z[a[j]] == z[a[i]]; j++){int fx = get(x[a[j]]), fy = get(y[a[j]]);if (fx == fy) continue; else cnt++;}for (j = i; j <= m&&z[a[j]] == z[a[i]]; j++){int fx = get(x[a[j]]), fy = get(y[a[j]]);if (fx == fy) continue; else fa[fx] = fy, ans += z[a[j]];}}if (cnt == n - 1) printf("%d\n", ans);else printf("Not Unique!\n");}return 0;}


0 0