标签:
题目链接:http://poj.org/problem?id=1679
判断最小生成数是否唯一:如果唯一这权值和次小生成树不同,否则相同;
#include<stdio.h> #include<string.h> #include<map> #include<iostream> #include<algorithm> #include<math.h> #define N 110 #define INF 0xfffffff using namespace std; int Max[N][N], used[N][N], vis[N], maps[N][N], dist[N], fa[N], n; void Init() { memset(vis, 0, sizeof(vis)); memset(used, 0, sizeof(used)); memset(Max, 0, sizeof(Max)); memset(fa, 0, sizeof(fa)); for(int i=0; i<=n; i++) { dist[i] = INF; for(int j=0; j<=n; j++) if(i == j) maps[i][j] = 0; else maps[i][j] = INF; } } int Prim(int start) { int ans=0; for(int i=1; i<=n; i++) { dist[i] = maps[start][i]; fa[i] = start; } vis[start] = 1; for(int i=1; i<=n; i++) { int Min = INF, index = -1; for(int j=1; j<=n; j++) { if(vis[j]==0 && Min > dist[j]) { Min = dist[j]; index = j; } } if(index == -1)break; vis[index] = 1; ans += Min; used[fa[index]][index] = used[index][fa[index]] = 1; for(int j=1; j<=n; j++) { if(vis[j] == 1 && index != j) { Max[index][j] = Max[j][index] = max(Max[fa[index]][j], dist[index]); } else if(vis[j] == 0 && dist[j] > maps[index][j]) { dist[j] = maps[index][j]; fa[j] = index; } } } return ans; } int SMST(int ans) { int Min = INF; for(int i=1; i<=n;i++) { for(int j=i+1; j<=n; j++) { if(used[i][j]==0 && maps[i][j] != INF) Min=min(Min, ans-Max[i][j]+maps[i][j]); } } return Min; } int main() { int T, m, a, b, c; scanf("%d", &T); while(T--) { scanf("%d%d", &n, &m); Init(); for(int i=0; i<m; i++) { scanf("%d%d%d", &a, &b, &c); maps[a][b] = maps[b][a] = c; } int num1 = Prim(1); int num2 = SMST(num1); if(num1 != num2) printf("%d\n", num1); else printf("Not Unique!\n"); } return 0; }
The Unique MST----poj1679次小生成树
标签:
原文地址:http://www.cnblogs.com/zhengguiping--9876/p/4680014.html