模板 最小生成树
Posted lovezxy520
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了模板 最小生成树相关的知识,希望对你有一定的参考价值。
prim:
给出一个无向图,求出最小生成树,如果该图不连通,则输出impossible。
#include<bits/stdc++.h> using namespace std; const int maxm = 200005; const int inf = 0x3f3f3f3f; struct edge int v, w, next; e[maxm << 1]; int cnt, n, m, sum, t, p, now = 1; int dis[5005], head[maxm], vis[5005]; int a, b, c; void add(int uu, int vv, int ww) e[++cnt].v = vv; e[cnt].w = ww; e[cnt].next = head[uu]; head[uu] = cnt; int main() cin >> n >> m; for(int i = 1; i <= m; i++) cin >> a >> b >> c; add(a, b, c); add(b, a, c); for(int i = 1; i <= n; i++) dis[i] = inf; for(int i = head[1]; i; i = e[i].next) dis[e[i].v] = min(e[i].w, dis[e[i].v]); while(++t < n) vis[now] = 1; int minn = inf; now = -1; for(int i = 1; i <= n; i++) if(!vis[i] && minn > dis[i]) minn = dis[i]; now = i; if(now == -1) cout << "impossible"; return 0; sum += minn; for(int i = head[now]; i; i = e[i].next) if(!vis[e[i].v] && e[i].w < dis[e[i].v]) dis[e[i].v] = e[i].w; cout << sum; return 0;
给出一个无向图,求出最小生成树。不用判断是否连通
#include<bits/stdc++.h> using namespace std; const int maxm = 200005; const int inf = 0x3f3f3f3f; struct edge int v, w, next; e[maxm << 1]; int cnt, n, m, sum, t, p, now = 1; int dis[5005], head[maxm], vis[5005]; int a, b, c; void add(int uu, int vv, int ww) e[++cnt].v = vv; e[cnt].w = ww; e[cnt].next = head[uu]; head[uu] = cnt; int main() cin >> n >> m; for(int i = 1; i <= m; i++) cin >> a >> b >> c; add(a, b, c); add(b, a, c); for(int i = 1; i <= n; i++) dis[i] = inf; for(int i = head[1]; i; i = e[i].next) dis[e[i].v] = min(e[i].w, dis[e[i].v]); while(++t < n) vis[now] = 1; int minn = inf; for(int i = 1; i <= n; i++) if(!vis[i] && minn > dis[i]) minn = dis[i]; now = i; if(dis[now] == inf) cout << "orz"; return 0; sum += minn; for(int i = head[now]; i; i = e[i].next) if(!vis[e[i].v] && e[i].w < dis[e[i].v]) dis[e[i].v] = e[i].w; cout << sum; return 0;
两者差别在于每次循环边时对now的处理
以上是关于模板 最小生成树的主要内容,如果未能解决你的问题,请参考以下文章