標籤:poj1679
The Unique MST
| Time Limit: 1000MS |
|
Memory Limit: 10000K |
| Total Submissions: 20421 |
|
Accepted: 7183 |
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 [email protected]
這題做得好開心,一次AC~
題意:給定一個聯通圖,判斷最小產生樹是否唯一。
題解:求出最小產生樹後再求次小產生樹,若次小產生樹的長度與最小產生樹相等就說明不唯一,否則唯一。
這是我的第一道次小產生樹題,在這裡總結下這個演算法:
利用一個矩陣max【】【】表示最小產生樹中任意兩點路徑上的最長邊權值(關鍵!!),在求最小產生樹時將已經選上的邊標記為已用,求完後,遍曆剩下未用的邊,這條邊若添加到最小樹中必定構成迴路,所以此時需要去掉原來樹中那條迴路中的最大值,也就是max矩陣儲存的值,所以問題轉換成找到一條未用的邊,使得它跟對應於max矩陣裡的邊差值最小,遍曆之後,次小產生樹的值即為原最小產生樹的值加上這個最小的差值。
#include <stdio.h>#include <string.h>#include <limits.h>#define maxn 102#define maxm (maxn * maxn) >> 1int head[maxn], max[maxn][maxn];struct Node{int u, v, cost, next;bool vis;} E[maxm];bool vis[maxn];int mini(int a, int b){return a < b ? a : b;}int prim(int n, int m){int u, i, tmp, j, len = 0, count = 0;memset(max, 0x7f, sizeof(max));memset(vis, 0, sizeof(vis));vis[1] = 1;while(count < n - 1){for(i = 1, tmp = INT_MAX; i <= n; ++i){if(!vis[i]) continue;for(j = head[i]; j != -1; j = E[j].next){if(vis[E[j].v]) continue;if(E[j].cost < tmp){tmp = E[j].cost; u = j;}}}++count; len += tmp;for(i = 1; i <= n; ++i){if(!vis[i]) continue;max[i][E[u].v] = max[E[u].v][i] = E[u].cost;}vis[E[u].v] = 1; E[u].vis = 1;}return len;}int getSecLen(int n, int m){int min = INT_MAX, u, v, w;for(int i = 0; i < m; ++i){if(E[i].vis) continue;u = E[i].u; v = E[i].v;w = E[i].cost;min = mini(min, w - max[u][v]);if(min == 0) return 0;}return min;}int main(){int t, n, m, i, minLen, secLen;scanf("%d", &t);while(t--){scanf("%d%d", &n, &m);memset(head, -1, sizeof(head));for(i = 0; i < m; ++i){scanf("%d%d%d", &E[i].u, &E[i].v, &E[i].cost);E[i].vis = 0; E[i].next = head[E[i].u];head[E[i].u] = i;}minLen = prim(n, m);secLen = getSecLen(n, m);if(secLen == 0) printf("Not Unique!\n");else printf("%d\n", minLen);}return 0;}