[Algorithm analysis and design] Kruskal minimum spanning tree algorithm and Prim's algorithm

Disclaimer: This article is a blogger original article, reproduced, please indicate the source https://blog.csdn.net/C2681595858/article/details/84104688


Experiment code (GitHub)

First, the experiment content

  • Achieve priority queue.
  • Kruskal implemented method of minimum spanning tree.
  • Achieve prim algorithm for minimum spanning tree.

Finally, the test with the following diagram:
Here Insert Picture Description

Second, theoretical knowledge

1 priority queue

  • Features: Find the insertion element and the value of the time complexity is log (n).
  • Realization of ideas: the use of a complete binary tree, all of the operations to ensure that the parent node of the child node is greater than (the magnitude relation between parent and child nodes only, no other requirements), so that the maximum value of the root.
  • Details:
    Since a child node must be greater than the parent, so the time to insert or delete sequentially adjusted, the adjustment method is as follows:
    Here Insert Picture Description
  • When inserted directly into the array elements of a final position, so that the tree is the rightmost leaf node of the lowermost layer (the upper right in FIG. 1 ). Then compare the size relationship between the leaf node and its parent, if the parent node is less than it, then swap their position, and so on until it is greater than the parent, to find the correct position. Because it is the worst-case scenario has been changing from a leaf node to the root, assuming that the number of layers from the tree of zero dollars, a total of stratum h. Then he changed h times. And where h = log (n), n is the total number of nodes. Therefore, the time complexity is log (n).
  • When you delete the last leaf node of the tree into the deleted position, then look at the size of the position and its relationship father and son, to move it. The worst situation is to remove the roots, then move when moved to and from the roots of the leaf nodes of the lowest level, and then it is inserted into the worst case the same are exchanged h times.

2, kruskal algorithm

  • To put it plainly, it is to find the right sides in all the remaining value of the minimum side, then see if it is added to the list, will not form a ring, if it does not constitute a ring added to the list, if it constitutes a ring, direct throw. After reading all the sides, and it will have a minimum spanning tree.

Specifically illustrated as follows:
Here Insert Picture Description
Here Insert Picture Description
Here Insert Picture Description

3, prim algorithm

  • The secant to use. Specific steps are as follows:
  1. Starting a node, draw a circle, circle the Lord Himself;
  2. Then the value was cut in the right side of the selected smallest edge, add to the mix, the draw a circle, trapping the already existing elements and add to the mix of elements.
  3. Look at the cut edge of the circle which, looking for a minimum of edge weights from them, add to the mix.
  4. And so on, until all vertices have come in time, and we will have a minimum spanning tree.
  5. FIG follows.
    Here Insert Picture Description
    Here Insert Picture Description
    Here Insert Picture Description
    Here Insert Picture Description

Here Insert Picture Description

Here Insert Picture Description
Here Insert Picture Description

Third, the experimental environment

  • Operating system and version: windows10
  • Compiler software and version: g ++ 6.3.0
  • Computer language used: c ++ language

Fourth, the experiment

  • The work is in previous work completed on the basis, which means that the underlying code structure, storage and earlier figures are the same, only the following highlights new interpretation algorithms implemented.

1 priority queue

  • Input: Represents a collection and the right side of the composition by weight of the two end points
  • Output: The minimum weight in the set of edges
  • Ideas:
    1. To make this a priority queue is universal, selected using templates.
    2. Due to pass in an object, since the need to compare the size of the sorting, it belongs to the object class should override the operator. In order to simplify the implementation of the program, the possible comparison operators used when sorting is defined between (>, <, ==).
      The main achievement of the following several functions:
  //insert a element into priority queue
  void insert(T ele_in);

  //get it root element, but not delete it
  T getHead();

  //get it root element, and delete it.
  T popHead();

  //get the length of queue
  int getSize();

It's private members have the following:

T* btree;//it will be used as a array.
  int length;
  int maxLength;
  • btree in the constructor for its application maxLength size of space, and its true length record length.
  • There is a private member function void ifResize();and then insert each time will determine whether to expand the btree space, if you need to expand, each time expanded to twice the original space.

2, prim algorithm

  • This algorithm because it generates only two sets in the calculation process, as compared to a simpler algorithm kruskal, and a function can be achieved as follows:
void Graph::prim(int startId)
{
  set<int> setInt;//这个集合用来存放已经被加进来的顶点
  setInt.insert(startId);
  cout<<"from     "<<"to        "<<"weigh\n";
  while(setInt.size() < this->vertexNumber)//until all vertexes add to setInt
  {
    Pritree<Node> pritree;
    for(set<int>::iterator it = setInt.begin(); it != setInt.end(); it++)
    {//把这个集合所有的割边都加进来
      Vertex* vertexPtr = this->headVertex;
      while(vertexPtr != NULL)
      {//先在顶点链表中找到set中的某个顶点
        if(vertexPtr->getVertexId() == (*it))
        {
          Node *nodePtr = vertexPtr->getHeadNode();
          while(nodePtr != NULL)
          {//然后再去看,这条边是不是割边,也就是看它指向的顶点是狗已经在setInt中了
						//如果这个顶点不再集合中,那么他就是一个待选顶点
            if(setInt.find(nodePtr->getToId()) == setInt.end())
            {//add cut edge to priority queue
              pritree.insert(*nodePtr);
            }
            nodePtr = nodePtr->getNextNode();
          }
          break;
        }
        vertexPtr = vertexPtr->getNextVertex();
      }
    }
    Node newNode = pritree.popHead();//弹出权值最小的边
    setInt.insert(newNode.getToId());//把这个边指向的顶点加进集合中
    cout<<newNode.getFromId()<<"        "<<newNode.getToId()<<"           "<<newNode.getWeight()<<endl;
  }
}

3, kruskal algorithm

  • Ideas: to achieve a two-dimensional dynamic array, a first row position of each of the record length of the line. Each row put a set, each set of elements as the number of changes dynamically changing the size of each row. If you find that there is an edge to be added to the list between the two sets, then both collections will be combined into one collection.
void Graph::kruskal()
{
  cout<<"from     "<<"to\n";
  Pritree<Node> pritree;
	initial(pritree);
	while(this->list_set[0][0] < this->vertexNumber+1)
	{
		Node newNode = pritree.popHead();
		//posf是fromId所在的集合下标,post是toId所在集合下标
		int posf = -1, post = -1;
		find(newNode,posf, post);
		if(posf != post)//如果这两个元素不再同一个集合中,那么合并这两个集合
		{
			cout<<newNode.getFromId()<<"        "<<newNode.getToId()<<"            "<<endl;
			merge(posf,post);
		}
	}
}
	void initial(Pritree<Node>& pritree);//负责把所有的边加进优先队列中
	void find(Node& newNode, int& posf, int& post);//查看两个元素是否在同一个集合中
	void merge(int& posf, int& post);//合并两个集合

Fifth, the experimental results

  • The final output is as follows: from the starting vertex represents, to reach the top indicates, weight represents the weight of the edge of the weight.
    Here Insert Picture Description
  • It is represented in the form of graphs:
    Prim:
    Here Insert Picture Description
    Kruskal:
    Here Insert Picture Description
  • This example, two algorithms seeking out the results just the same.

Six experimental summary

  • In doing kruskal algorithm, we encountered difficulties, how to group the vertices, do not know how many groups there will be, not open space, the final choice of dynamic arrays, is spent on the delete, died on the way to use the application. The final is made out, but it feels very bad but, of course, is before the specific algorithm in kruskl teacher.

  1. Figure taken from Liu teacher PPT ↩︎

Guess you like

Origin blog.csdn.net/C2681595858/article/details/84104688
Recommended