Brief minimum spanning tree algorithm

Minimum spanning tree


The next is to introduce minimum spanning tree content.

What is the minimum spanning tree?

Definition: the cost of each side and the minimum spanning tree is called the minimum cost spanning tree communication network (Minimum Cost Spanning Tree), referred to as the minimum spanning tree.

There are many algorithms that form the minimum spanning tree algorithm is the use of most of the properties of a lowermost spanning tree:

Properties: Suppose N = (V, E) is a communication network, U is a nonempty subset of the set of vertices V. If (u, v) is the one with the smallest weight (or expense) side, which u∈U, v∈VU, then there must be a minimum spanning tree contains the edge (u, v) of

To sum up, we must have these conditions:

  • Is a communication network (FIG communication)
  • Each side has the right value

If you do not know, so let's give an example:

Let's say we need to build a network of contacts in the n cities, because of the large cities, we of course impossible to communicate to them all, considering the price, we have to use in order to minimize the cost of connectivity for all cities.

? How to do it so hard (っ ° Д °;) っ


We use circles to represent each city

all

With the values ​​contained in the arrow denoted weights

part1

Our question is, how do we choose to go to achieve our purpose? (Our aim is: Demacian d ===== (¯ ▽ ¯ *) b ....... .... course objective is to select a few routes, the minimum value of the composition weight, and be able to these connection points on ......)

First, we observe with your eyes ..... then we can easily select which several routes:

part2

Then we calculate the total weights is: 1 + 2 + 4 + 5 + 12 = 24. Yes, this is the minimum spanning tree structure, we selected route is not wrong. So the question came. We are how to pick it?

Remember when we choose just the way it? My thinking is, first according to their respective sides of the weights in ascending order, then drained sequence, and then to choose the edge I need, until the completion of all the points covered, of course, if there is an edge is present in the between two vertices have even been, I do not, because the two cities have gone through (● ∀ ●).

When all vertices are connected, we will constitute the minimum spanning tree. If we are so drained order such a sequence:

city City may pass Weight
A B 1
A D 2
B F 4
A E 5
E F 9
A C 12
B C 13
C D 18
D E 32

Then it is converted into a digital ABCDEF corresponds: 123456

We then small to large, choice is the following situation:
choose1
choose2
choose3
choose4
choose5

Since we have six points, we select five sides, completed the minimum spanning tree we need. Yes, this is an algorithm minimum spanning tree I would say: (Kruskal Kruskal algorithm)

Compare the official construction process is:

  • Suppose the communication network N = (V, E), in the N side-by-weight ascending order
  • FIG non-communication is only the initial state of n vertices and endless T = (V, {}), each vertex in FIG communication self-contained component.
  • Select the minimum weight in the edge E, if the vertices of the edges attached to different connected components fall in the T (i.e., no loop is formed), this is added to the T side, otherwise this edge rounding at a selected minimum weight edge
  • Repeat until all the vertices until the T in the same connected component

A wave of official explanation, looked at me a bit ignorant (@ _ @), but all right, I have my own understanding. Next is the code that implements ......


main.cpp

#include"GraphKruskal.h"

int main()
{
    GraphKurskal g1;
    g1.Init();
    g1.Kruskal();
    g1.Display();
    return 0;
}

/*
输入样例:
1 1 1
1 4 2
2 6 4
1 5 5
5 6 9
1 3 12
2 3 13
3 4 18
4 5 32

*/

GraphKruskal.h

#pragma once
#ifndef _GRAPHKRUSKAL_H_
#define _GRAPHKRUSKAL_H_
#include<iostream>
#include<algorithm>
#include<cstdlib>
#include<vector>
using namespace std;
//  这是利用邻接矩阵来实现的克鲁斯卡尔搜索最小生成树的算法
struct node
{
    int from, to;
    int sideID;//记录边号,已选定可以输出的边
    int distance;
};

class GraphKurskal
{
private:
    vector<node>graph;//记录边
    vector<bool>visited;//是否经历过
    vector<int>IDofSide;//每条边的ID
    int minDistacne;//最小权值
    int nodeNumber;//几个点

    //void Sort();//这个程序是调用库函数的sort函数进行排序,因此没有写自定义sort函数
public:
    void Init();//初始化
    void Kruskal();//进行克鲁斯卡尔算法,找到最小生成树
    void Display();//显示

};
bool cmp(node a1,node a2);//从小到大排序的函数

#endif // !_GRAPHKRUSKAL_H_

GraphKruskal.cpp

#include "GraphKruskal.h"


void GraphKurskal::Init()
{
    node n1;
    int i = 0;
    cout << "请输入有几个点" << endl;
    cin >> nodeNumber;
    visited.resize(nodeNumber + 1, false);
    cout << "请输入各边的关系,'#'结束" << endl;
    cout << "请按照格式:开始点---终止点---距离" << endl;
    while ((cin >> n1.from&& n1.from != '#') && (cin >> n1.to&& n1.to != '#'))
    {
        cin >> n1.distance;
        n1.sideID = ++i;
        graph.push_back(n1);
    }
}

void GraphKurskal::Kruskal()
{

    sort(graph.begin(), graph.end(),cmp);//进行函数比较
        //当选择的边数不为节点数减一的情况,我们继续循环
    minDistacne = 0;
    for (int i = 0; i < graph.size(); i++)
    {
        //判断图中的点是否遍历过,如果遍历过,那么跳过,否则继续遍历
        if (!visited[graph[i].from] || !visited[graph[i].to])
        {
            visited[graph[i].from] = true;
            visited[graph[i].to] = true;
            IDofSide.push_back(graph[i].sideID);
            minDistacne += graph[i].distance;
            if (IDofSide.size() == nodeNumber - 1)
                break;
        }
    }
}

void GraphKurskal::Display()
{
    cout << "总距离是:" << minDistacne << endl<<"权边是:";
    for (int i = 0; i < IDofSide.size(); i++)
        cout << graph[IDofSide[i]-1].distance << " ";
    cout << endl;
}

bool cmp(node a1, node a2)
{
    return a1.distance > a2.distance ? false : true;
}

Code to achieve results:
show1


Learn "data structure C language version | Version 2"


Guess you like

Origin www.cnblogs.com/Yunrui-blogs/p/11884247.html