Today wrote a minimum spanning tree algorithm, also to prepare the Blue Bridge Cup. The first is to discuss the algorithm.
The algorithm principle of the minimum spanning tree I always knew that the code would never write. Simply say the principle is good. A non-circular graph with corresponding weights on each edge, and the smallest spanning tree to find the right value and the minimum spanning tree. First, all the points are divided into two set u,v. where u is the point where the corresponding edge has been found. Each time you look for the shortest side of the U to V, and add the edge to the end of the V to U. Loop down until all the points are found.
Inspired by http://blog.chinaunix.net/uid-25324849-id-2182922.html
Here is the code, the note is clear (the point distance is not connected to infinity, oneself to oneself is also infinity)
1#include <iostream>2#include <stack>3#include <stdio.h>4#include <string.h>5 using namespacestd;6 Const int inch= +;7 intMain ()8 {9 intmap[5][5] = {{inch, -,inch,inch,inch},{ -,inch, +, +, -},{inch, +,inch, -, +},{inch, +, -,inch, -},{inch, -, +, -,inch}};Ten intcost[5];//The shortest distance from points in the current point collection to other points One intpoint[5];//edges within the set (I,point[i]) A BOOLvisit[5];//the point is not within the collection - intfather[5];//It doesn't seem to work . - inti; the //First point is added to the collection and the array is assigned a value - for(i =0; I <5; i++) - { -Cost[i] = map[0][i]; +Point[i] =0; -Visit[i] =false; +Father[i] =0; A } atvisit[0] =true; - intK; - //there are n vertices that have n-1 edges and n-1 cycles to find these edges. - for(k =1; k <5; k++) - { - intj =0; in intMin =inch; - //find the point with the shortest distance from the set within the collection to for(i =0; I <5; i++) + { - the if(!visit[i] && min > Cost[i]) {min = Cost[i];j =i;} * } $ //Add this point to the collectionPanax NotoginsengVISIT[J] =true; -FATHER[J] =Point[j]; the //Update Arrays + for(i =0; I <5; i++) A { the //for points that are not in the set, change the cost array if the distance from the newly added point is less than the original distance . + //and change the other end of the point to the newly added point . - //I is not a point in the collection, J is the point just joined $ if(!visit[i] && cost[i]>map[j][i]) {Cost[i] = Map[j][i];p Oint[i] =J;} $ } -cout<<j<<" "<<point[j]<<endl;//print out this newly added edge - } the intsum =0; - for(i =1; I <5; i++)Wuyi { theSum + =Map[i][point[i]]; - } Wucout<<sum;//the sum of the weights of the minimum spanning tree - return 0; About}
View Code
The algorithm of minimum spanning tree