标签:
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 25203 | Accepted: 8995 |
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!
题意:问一棵最小生成树是否唯一
找次小生成树,如果相等不唯一,否则唯一
次小生成树:就是最小生成树换一条边而成的生成树;用maxd【x】【y】存储最小生成树两个节点(x,y)路径中最大的那条边的权值,也就是最小生成树中x-z-...-y中那个最大的那一个权值,然后就可以换边了,到底换哪一个边就从不在生成树中的边一个一个枚举咯,假设x-y,如果要用x-y替换x-z...-y肯定得替换x-z...-y中权值最大的那条边才能让最后得到结果只比x-z...-y小一点,也就是仅次于
1 #include <iostream> 2 #include <cstdio> 3 #include <algorithm> 4 #include <cstring> 5 using namespace std; 6 const int MAX = 110; 7 const int INF = 100000000; 8 int n,m,ans,cnt; 9 int edge[MAX][MAX],vis[MAX],used[MAX][MAX],dist[MAX]; 10 int pre[MAX],maxd[MAX][MAX]; 11 void prime() 12 { 13 memset(vis,0,sizeof(vis)); 14 memset(used,false,sizeof(used)); 15 memset(maxd,0,sizeof(maxd)); 16 for(int i = 1; i <= n; i++) 17 { 18 dist[i] = edge[1][i]; 19 pre[i] = 1; 20 } 21 vis[1] = 1; 22 pre[1] = -1; 23 for(int i = 1; i < n; i++) 24 { 25 int minn = INF,pos; 26 for(int j = 1; j <= n; j++) 27 { 28 if(vis[j] == 0 && dist[j] < minn) 29 { 30 minn = dist[j]; 31 pos = j; 32 } 33 } 34 if(minn == INF) 35 { 36 ans = INF; 37 return; 38 } 39 ans += minn; 40 vis[pos] = 1; 41 used[pos][pre[pos]] = used[ pre[pos] ][pos] = true; 42 for(int j = 1; j <= n; j++) 43 { 44 if(vis[j]) 45 maxd[j][pos] = maxd[pos][j] = max(dist[pos], maxd[j][pre[pos]]); 46 if(vis[j] == 0 && dist[j] > edge[pos][j]) 47 { 48 dist[j] = edge[pos][j]; 49 pre[j] = pos; 50 } 51 } 52 } 53 } 54 void smst() 55 { 56 cnt = INF; 57 for(int i = 1; i <= n; i++) 58 { 59 for(int j = i + 1; j <= n; j++) 60 { 61 if(used[i][j] == false && edge[i][j] != INF) 62 { 63 cnt = min(cnt, ans - maxd[i][j] + edge[i][j]); 64 } 65 } 66 } 67 } 68 int main() 69 { 70 int t; 71 scanf("%d", &t); 72 while(t--) 73 { 74 for(int i = 1; i <= n; i++) 75 for(int j = i + 1; j <= n; j++) 76 { 77 edge[i][i] = 0; 78 edge[i][j] = edge[j][i] = INF; 79 } 80 scanf("%d%d", &n,&m); 81 for(int i = 0; i < m; i++) 82 { 83 int x,y,w; 84 scanf("%d%d%d", &x, &y, &w); 85 edge[x][y] = edge[y][x] = w; 86 } 87 ans = 0; 88 prime(); 89 smst(); 90 if(ans == INF) 91 { 92 printf("Not Unique!\n"); 93 continue; 94 } 95 if(cnt == ans) 96 { 97 printf("Not Unique!\n"); 98 } 99 else 100 { 101 printf("%d\n",ans); 102 } 103 } 104 return 0; 105 }
标签:
原文地址:http://www.cnblogs.com/zhaopAC/p/4986175.html