标签:
http://poj.org/problem?id=1679
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 23339 | Accepted: 8284 |
Description
Input
Output
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<stdio.h> #include<string.h> #include<math.h> #include<ctype.h> #include<stdlib.h> #define INF 0x3f3f3f3f #define max(a, b)(a > b ? a : b) #define min(a, b)(a < b ? a : b) #define N 110 int maps[N][N], Max[N][N];//maps[i][j]线段线段ij的花费,Max记录树外最大的线段的花费 int dist[N], f[N], n;//f[i] i的父节点即将点i连入树的起点,dist[i]将i连入树需要的花费 bool vis[N], use[N][N];//vis[i]标记点i是否在树种,use[i][j]标记线段ij是否在树中 void Init()//初始化 { memset(vis, false, sizeof(vis)); memset(use, false, sizeof(use)); memset(dist, 0, sizeof(dist)); memset(f, 0, sizeof(f)); int i, j; for(i = 0 ; i < N ; i++) { for(j = 0 ; j < N ; j++) { if(i == j) maps[i][j] = 0; else maps[i][j] = INF; } } } int prim(int s)//求最小生成树 { int index, Min, i, j, ans = 0; for(i = 1 ; i <= n ; i++) { dist[i] = maps[s][i]; f[i] = s; } vis[s] = true; for(i = 1 ; i < n ; i++) { Min = INF; for(j = 1 ; j <= n ; j++) { if(!vis[j] && dist[j] < Min) { Min = dist[j]; index = j; } } vis[index] = true; ans += Min; use[f[index]][index] = use[index][f[index]] = true; for(j = 1 ; j <= n ; j++) { if(vis[j] && index != j) Max[index][j] = Max[j][index] = max(Max[f[index]][j], maps[f[index]][index]); if(!vis[j] && dist[j] > maps[index][j]) { dist[j] = maps[index][j]; f[j] = index; } } } return ans; } int SMST(int num)//求次小生成树 { int i, j, Min = INF; for(i = 1 ; i < n ; i++) { for(j = i + 1 ; j <= n ; j++) { if(!use[i][j] && maps[i][j] != INF) Min = min(Min, num + maps[i][j] - Max[i][j]); } } return Min; } int main() { int t, m, x, y, w, num1, num2; scanf("%d", &t); while(t--) { Init(); scanf("%d%d", &n, &m); while(m--) { scanf("%d%d%d", &x, &y, &w); maps[x][y] = maps[y][x] = w; } num1 = prim(1); num2 = SMST(num1); if(num1 == num2)//最小生成树与次小生成树相等,则最小生成树不唯一 printf("Not Unique!\n"); else printf("%d\n", num1); } return 0; }
poj 1679 http://poj.org/problem?id=1679
标签:
原文地址:http://www.cnblogs.com/qq2424260747/p/4676132.html