Prim minimum spanning tree algorithm based on the nature of the MST

Disclaimer: This article is a blogger original article, reproduced, please attach Ming source ^ _ ^ https://blog.csdn.net/cprimesplus/article/details/90214800

The concept of the minimum spanning tree

Assuming  n the road between the cities, the China Unicom  n cities only  n-1 road strip. The purpose is to make the total road spending a minimum, seeking the best solution.

 

MST nature

MST (Most Spanning Tree) Nature namely:

Minimum spanning tree nature: Let G = (V, E) is a communication network, U is a non-empty subset of the set of vertices V. If the (u, v) G is in a "U in an endpoint (e.g.: u∈U), the other end of the edge is not U (for example: v∈VU), and (u, v) having a minimum weight , then there is a minimum spanning tree of G include this edge (u, v).

Description vernacular namely:

Unicom network for all nodes constituting a set, from a subset of either take referred to as u, set by subtracting a small subset of the set referred to is configured v. Find the minimum weight of a path from u to v, then this path must belong to the minimum spanning tree Unicom network.

 

MST proof properties and appreciated

Reductio ad absurdum, see Yan Wei Min version of "data structure" P173.

Prim little understanding of the algorithm:

Why this structure is composed of a tree (no ring)? Prim thinking can be found by step algorithm:

(1) when the first set of points u only one element, adding a new node constituting the path can not form a ring.

(2) When the node u of not less than 3, then a path is unlikely to be added to the ring, may constitute as before with the new node into the ring node has been placed in u.

 

Prim minimum spanning tree algorithm codes

// Prime算法求图的最小生成树
#include<iostream>
#include<cstring>
#define MAX_SIZE 128
#define INF 0x3f3f3f3f
using namespace std;
int Graph[MAX_SIZE][MAX_SIZE], vexnum; 
int MSTByPrim()
{
	int vis[MAX_SIZE];   // 辅助数组,用来记录一个点是否已经被加入到割集U,不加这个辅助数组的话还需要再遍历U 判断一个点是否在U 中
	int U[MAX_SIZE];
	memset(vis, 0 ,sizeof(vis));
	vis[0] = 1;			// 最初放入顶点A
	U[0] = 0;
	int res = 0;
	int index = 1;
	while(index < vexnum)
	{
		int min_val = INF, temp = 0, markU = 0;
		for(int i = 0;i < index;i++){
			for(int j = 0;j < vexnum;j++){
				if(!vis[j] && Graph[U[i]][j]<min_val){
					min_val = Graph[U[i]][j];
					markU = U[i];
					temp = j;	
				}
			}
		}
		cout<<(char)(markU+'A')<<"-->"<<(char)(temp+'A')<<' '<<min_val<<endl;
		vis[temp] = 1;
		res += min_val;
		U[index++] = temp;
	}
	return res;
}
int main()
{
	cin>>vexnum;
	for(int i = 0;i < vexnum;i++)
		for(int j = 0;j < vexnum;j++){
			 cin>>Graph[i][j];
			 if(!Graph[i][j]) Graph[i][j] = INF;
		}
	cout<<MSTByPrim();
	return 0;
}                                      

Test cases and results

Guess you like

Origin blog.csdn.net/cprimesplus/article/details/90214800