Minimum spanning tree:
In a given connected undirected graph G = (V, E) ,(U, v) represents the edge of the connection vertex u and vertex V , and W (u, v) represents the weight of this edge, if there is a subset of G and no loop graph, so that W (T) is the smallest , this T is the smallest spanning tree of G.
Basic ideas:
The Kruskal algorithm selects a total of n-1 edges, and the greedy rule used is to select from the remaining edges a collection with the least expensive edges that do not produce loops to join the selected edges. It is not possible to form a spanning tree if the selected edges produce loops. The Kruskal algorithm is divided into e - steps, where e is the number of edges in the network. Consider this e -edge in an incremental order, with one edge at a time. When an edge is considered, if a loop is added to the set of selected edges, it is discarded, otherwise it is selected.
Summarized as follows:
1. The edge of G is not descending by weight.
2. Once take the least weight of the edge, if you put it into the T will not form a loop, then put it into T , otherwise it will be discarded.
Determine if a loop is formed and a set is found.
Pseudo code:
Algorithm Analysis:
The main cost is the sort of side, the time complexity is O (MLOGM).
C++Code:
struct Edge {int u, V, c;bool operator < (const edge &b) Const {return c < B.C;}} E[mxe];int N, m;int fa[mnx];int find (int x) {if (fa[x]! = x) fa[x] = find (fa[x]); return fa[x];} Kruskal Complexity O (| E|log| e|), | E|: The number of sides int Kruskal () {sort (E + 1, E + M + 1); Edge sort for (int i = 1; I <= n; ++i) fa[i] = i; And check the set initialization int ret = 0;for (int i = 1; I <= m; ++i) {int u = e[i].u, v = e[i].v, c = e[i].c;u = Find (u), V = Find (v), if (U!) = v) {//not within the same set, add this edge as part of the minimum spanning tree ret + = c;fa[u] = v;}} return ret;}
016-kruskal algorithm-greedy-"algorithmic design techniques and analysis" M.H.A study notes