次小生成树 - 堆优化
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了次小生成树 - 堆优化相关的知识,希望对你有一定的参考价值。
const int inf = 1<<29; int n, m; int edge[105][105]; bool vis[105]; int d[105]; int mm[105][105]; int pre[105]; bool used[105][105]; struct node { int v, c; node(int _v = 0, int _c = 0):v(_v), c(_c){} friend bool operator< (node n1, node n2){ return n1.c > n2.c; } }; int ans, ans2; void prim(){ priority_queue<node>que; while(!que.empty()) que.pop(); memset(mm, 0, sizeof(mm)); memset(pre, 0, sizeof(pre)); memset(used, false, sizeof(used)); memset(vis, false, sizeof(vis)); for(int i = 1; i <= n; i++){ d[i] = edge[1][i]; pre[i] = 1; if (d[i] < inf) { que.push(node(i, d[i])); } } vis[1] = true; ans = 0; int cnt = 0; while(!que.empty()){ node tem = que.top(); que.pop(); int v = tem.v; int c = tem.c; if (vis[v]) continue; vis[v] = true; ans += c; cnt++; used[v][pre[v]] = used[pre[v]][v] = true; for(int i = 1; i <= n; i++){ if (vis[i]) mm[i][v] = mm[v][i] = max(d[v], mm[i][pre[v]]); if (!vis[i] && edge[v][i] < d[i]){ d[i] = edge[v][i]; pre[i] = v; que.push(node(i, d[i])); } } if (cnt == n - 1) break; } if (cnt < n-1) ans = -1; } void fun(){ ans2 = inf; for(int i = 1; i <= n; i++){ for(int j = 1; j <= n; j++){ if (!used[i][j] && edge[i][j] < inf){ ans2 = min(ans2, ans+edge[i][j]-mm[i][j]); } } } }
以上是关于次小生成树 - 堆优化的主要内容,如果未能解决你的问题,请参考以下文章