prim:
given an undirected graph, the minimum spanning tree is obtained, if this figure is not connected, the output 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; }
It gives an undirected graph, a minimum spanning tree is obtained. Do not judge whether communication
#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; }
In that the difference between the two sides of each loop of the process now of