# Kruskal && Prim Templates

Source: Internet
Author: User

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

Related Keywords:

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

## A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

• #### Sales Support

1 on 1 presale consultation

• #### After-Sales Support

24/7 Technical Support 6 Free Tickets per Quarter Faster Response

• Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.