[C ++] Minimum Spanning Tree

1. The minimum spanning tree is defined

example
Trees that are not loop diagram, Spanning Tree refers to a map to delete some of the top side, so that it does not loop.
Minimum spanning tree refers to the right side of the spanning tree and the smallest kind.
FIG minimum spanning tree is on this:
answer

2. Prim algorithm

2.1 The algorithm processes

For the above figure as an example:

  1. First select a starting point, we have to A as an example.
  2. Create a set S, it has been used to store the intermediate point of the tree. A start bit set bird, i.e., $ S = {A} $.
  3. Selecting a communication to a minimum set point S side, the other end where it is not in the set S. To ensure that the minimum spanning tree will not form a ring. This set of end edges S is not in the set of S added. (Currently choose sides AB, $ S = {A, B} $)
  4. Step three was repeated until all points in the set S.
  5. The answer is the right side of the edge and it just selected.

Time complexity: $$ O (nm + m) $$

2.2. Optimization

This time the main bottleneck of the algorithm is in the right side we find the smallest one side of that time, then this can actually be noticed by heap optimization. code show as below:

int ans = 0;
int index = 1;
h.push(point(0, 1));
while (index <= n) {
    int x = h.top().id, d = h.top().w;
    h.pop();
    if (S[x]) continue;
    S[x] = 1;
    ++index;
    ans += d;
    for (int i = 0; i < G[x].size(); ++i) {
        int y = G[x][i].v, z = G[x][i].w;
        if (!S[y]) {
            h.push(point(z, y));
        }
    }
}

Time complexity: $ O (n \ log m + m) $

3. kruskal algorithm

3.1 The algorithm processes

Or above figure as an example:

  1. The first step the beginning, give the edge to sort.
  2. Selecting a minimum of the right side edge, it is determined whether the original has two communication endpoints, if there is no communication, then it is selected from this edge. To ensure that the trees will not loop.
  3. Step two is repeated until the election $ $ n-1 until the edges.
  4. The above process is to get the minimum spanning tree.

Time complexity: $ O (n ^ 2) $

3.2. Optimization

The main bottleneck algorithm is the time to determine how the original two points connected and if the DFS or BFS, it is less efficient, so we're using disjoint-set optimization.

sort(E.begin(), E.end(), cmp);
int index = 1, np = 0;
int ans = 0;
while (index <= n - 1) {
    if (np >= E.size()) break;
    node now = E[np++];
    if (getf(now.u) == getf(now.v)) continue;
    ++index;
    ans += now.w;
    merage(now.u, now.v);
}

Time complexity: $ O (m \ log m + m \ alpha (n)) $

==by szdytom ==

Guess you like

Origin www.cnblogs.com/szdytom/p/11622045.html