首页 > 代码库 > POJ 1679 The Unique MST

POJ 1679 The Unique MST

The Unique MST
Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 19847 Accepted: 6959

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

23 31 2 12 3 23 1 34 41 2 22 3 23 4 24 1 2

Sample Output

3Not Unique!

Source

POJ Monthly--2004.06.27 srbga@POJ
 
解题:测试数据好像有问题啊,大大的问题。。。下面写法貌似只能过这题
 
 1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <cstdlib> 5 #include <vector> 6 #include <climits> 7 #include <algorithm> 8 #include <cmath> 9 #define LL long long10 #define INF 0x3f3f3f11 using namespace std;12 int mp[101][101],d[101];13 int n,m;14 bool vis[101];15 int prim(){16     int i,j,k,temp,index,ans = 0;17     for(i = 1; i <= n; i++) d[i] = INF;18     d[1] = 0;19     memset(vis,false,sizeof(vis));20     for(i = 0; i < n; i++){21         temp = INF;22         for(j = 1; j <= n; j++)23             if(!vis[j] && d[j] < temp) temp = d[index = j];24         k = 0;25         for(j = 1; j <= n; j++){26             if(vis[j] && mp[index][j] == temp) k++;27         }28         if(k > 1) return -1;29         vis[index] = true;30         ans += temp;31         for(j = 1; j <= n; j++){32             if(!vis[j] && d[j] > mp[index][j]) d[j] = mp[index][j];33         }34     }35     return ans;36 }37 int main(){38     int ks,i,j,u,v,w;39     scanf("%d",&ks);40     while(ks--){41         scanf("%d%d",&n,&m);42         for(i = 0; i <= n; i++)43             for(j = 0; j <= n; j++)44             mp[i][j] = INF;45         for(i = 0; i < m; i++){46             scanf("%d%d%d",&u,&v,&w);47             if(mp[u][v] > w){48                 mp[u][v] = mp[v][u] = w;49             }50         }51         w = prim();52         if(w < 0) puts("Not Unique!");53         else printf("%d\n",w);54     }55     return 0;56 }
View Code