标签:cin one repr ++ div class sum -- mst
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!
求次小生成树 看与最小生成树是否相同
prime求次小生成树
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <cmath> #include <queue> #define mem(a, b) memset(a, b, sizeof(a)) using namespace std; const int maxn = 10010, INF = 0x7fffffff; typedef long long LL; int graph[510][510], d[maxn], vis[maxn], maxd[510][510], pre[maxn]; int n, m; int prime(int s) { int temp, sum = 0; mem(vis, 0); for(int i=1; i<=n; i++) d[i] = graph[s][i], pre[i] = s; vis[s] = 1; d[s] = 0; for(int i=1; i<n; i++) { int mincost = INF; for(int j=1; j<=n; j++) { if(!vis[j] && mincost > d[j]) mincost = d[j], temp = j; } for(int j=1; j<=n; j++) if(vis[j]) maxd[temp][j] = maxd[j][temp] = max(mincost, maxd[pre[temp]][j]); vis[temp] = 1; sum += mincost; for(int j=1; j<=n; j++) { if(!vis[j] && d[j] > graph[temp][j]) d[j] = graph[temp][j], pre[j] = temp; } } // for(int i=1; i<=n; i++) // sum += d[i]; return sum; } int main() { int T; cin>> T; while(T--) { cin>> n >> m; for(int i=1; i<=n; i++) for(int j=1; j<=n; j++) if(i == j) graph[i][j] = 0; else graph[i][j] = graph[j][i] = INF; for(int i=0; i<m; i++) { int u, v, w; cin>> u >> v >> w; graph[u][v] = graph[v][u] = w; } int sum = prime(1); int lsum = INF; for(int i=1; i<=n; i++) for(int j=i+1; j<=n; j++) { if(i != pre[j] && j != pre[i] && graph[i][j] != INF) if(sum - maxd[i][j] + graph[i][j] < lsum) lsum = sum - maxd[i][j] + graph[i][j]; } if(lsum == sum) cout<< "Not Unique!" <<endl; else cout<< sum <<endl; } return 0; }
The Unique MST POJ - 1679 (次小生成树)
标签:cin one repr ++ div class sum -- mst
原文地址:https://www.cnblogs.com/WTSRUVF/p/9280124.html