标签:void pos std col 模板 ble 无向图 连通 its
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的处理
标签:void pos std col 模板 ble 无向图 连通 its
原文地址:https://www.cnblogs.com/lovezxy520/p/11615273.html