1. Kruskal (and set template):
/*kruskal: And check the realization, record two points and distance, sorted by distance ascending, O (eloge) */struct edge{int u, V, w;bool operator < (const Edge &r) Const {return W < R.W;}} Edge[e];sort (edge+1, Edge+1+m), if (!uf.same (x, y)) uf. Union (x, y), ans + = w;
2. Prim:
O (n ^ 2):
/*prim:dijkstra thought, adjacency matrix implementation, suitable for dense graphs, O (n ^ 2) not connected return-1, or return minimum spanning tree length (MST) */int Prim (int s) {memset (Vis, false, sizeof (VIS)); memset (d, INF, sizeof (d));d [s] = 0;int ret = 0;for (int i=1; i<=n; ++i) {int mn = INF, u = -1;for (int i=1; i<=n; + +i) {if (!vis[i] && d[i] < mn) MN = d[u=i];} if (U = =-1) return-1;vis[u] = True;ret + = d[u];for (int i=1; i<=n; ++i) {if (!vis[i] && d[i] > W[u][i]) {D[i] = W[u][i];}} return ret;}
O (ELOGV):
/*prim:dijkstra thought, Priority queue optimization, suitable for sparse graphs, O (ELOGV) Not connected return-1, or return minimum spanning tree length (MST) */int Prim (int s) {memset (Vis, false, sizeof (VIS)); memset (d, INF, sizeof (d));p riority_queue<edge> q;for (int i=head[s]; ~i; i=edge[i].nex) {int v = edge[i].v, W = edg E[i].w;if (D[v] > W) {d[v] = W; Q.push (Edge (V, d[v));}} Vis[s] = True;d[s] = 0;int ret = 0;while (! Q.empty ()) {int u = q.top (). V; Q.pop (), if (Vis[u]) continue;vis[u] = True;ret + = d[u];for (int i=head[u]; ~i; i=edge[i].nex) {int v = edge[i].v, W = edge[ I].w;if (!vis[v] && D[v] > W) {d[v] = W; Q.push (Edge (V, D[v]);}}} return ret;}
Kruskal && Prim Templates