C + + minimum spanning tree prim (PRIMM) algorithm __web

Source: Internet
Author: User
Prim (Primm) algorithm of minimum spanning tree
minimum Spanning Treeis to seek a tree T in a given v,e graph G, so that the tree has all the vertices in the graph G, all edges are from the edges in the graph G, and the Benquan of the whole tree is the smallest.
As shown above, a graph G and its minimum spanning tree T are given, where the red line is the edge of the minimum spanning tree. The minimum spanning tree T contains all the vertices in Figure g, and the sum of the Benquan of the trees they generate is 15, which is the smallest of all spanning tree weights. The minimum spanning tree has 3 properties: (1) The minimum spanning tree is a tree, so the number of edges equals the fixed-point number minus 1, and there must be no ring in the tree; (2) for a given graph G (v,e), the minimum spanning tree may not be unique, but the sum of its edges must be unique; (3) Since the minimum spanning tree is generated on the graph, So the root node can be any node in the tree.
Prim AlgorithmPrim algorithm is used to solve the problem of minimal spanning tree. Basic idea:Sets the set S in Graph G (v,e), stores the vertices that have been accessed, and then each time from the set v-s selects the smallest vertex of the shortest distance from the set S (recorded u), accessing and adding the set S. After that, the vertex U is the mediation point that optimizes all the shortest distances between the vertex V and the set S that can be reached from U. Such an operation performs n times (n is the number of vertices) until the set S already contains all vertices. Note: It can be found that the idea of the prim algorithm is almost identical to the Dijkstra algorithm in the shortest path, but the set S is used instead of the starting point s in the Dijkstra algorithm when the shortest distance is involved. Here's an example of how prim is seeking the smallest spanning tree. Assuming that the vertex V0 begins, the current collection V={v0,v1,v2,v3,v4,v5} (blue), the collection s={} (yellow), the distance between vertex V0 and set S is 0, and the other is INF (a large number): (1) as shown in figure (a), select the vertex V0 with the smallest set S distance, To add it to the set S, and connecting the vertices V0 with the other vertices, at which point the set V={V1,V2,V3,V4,V5}, the Set S={v0}, (2) as shown in figure (b), select the vertex V4 that is the smallest from the set S, add it to the set S, and connect the vertex V4 to the edges of the other vertices. Set V={V1,V2,V3,V5}, set S={v0,v4}, (3) as shown in figure (c), select the vertex V5 that is the smallest from the set S, add it to the set S, and connect the vertex V5 to the edges of the other vertices, at which point the collection V={v1,v2,v3}, set s={v0,v4,v5 (4) as shown in figure (d), select the vertex V1 that is the least distance from the set S, add it to the set S, and connect the vertices V1 with the other vertices, at which point the collection V={v2,v3}, the collection s={v0,v1,v4. V5}; (5) as shown in Figure (e), select the vertex V3 that is the smallest from the set S, add it to the set S, and connect the vertices V3 with the other vertices, at which point the set V={v2}, the Set S={V0,V1,V3,V4,V5}, (6) as shown (f), and the vertex V2, the last choice, Add it to the set S, at which point the set v={}, the collection s={v0,v1,v2,v3,v4,v5}; The set S already contains all vertices, and the algorithm ends.


Prim algorithm Flow:Set S for Figure G (v,e), store the vertex that has been accessed, and then execute n times the following two steps (n is the number of vertices): each time from the set v-s select the smallest vertex of the shortest distance from the set S (Note u), access and add the set S, and add the nearest edge of the set to the minimum spanning tree. The vertex u is the mediation point that optimizes all the shortest distances between the unreachable vertex V and the set S that can be reached from U. Specific implementation:The prim algorithm needs to implement two key concepts, the implementation of set S, the shortest distance between Vertex VI (0<=I<=N-1) and set S. The implementation of set S uses a bool-type array vis[] to indicate whether the vertex has been accessed, where the vis[i]=true indicates that Vertex VI has been accessed, and vis[i]=false the vertex vi is not accessed, and the INT-type array d[] to hold the shortest distance between the vertex VI and the set S. At the beginning, except for the d[s]=0 of the start S, the rest of the vertices are assigned a large number to represent the INF, which is not up to. Pseudo code is as follows:
G is the graph, and the array d is the shortest distance
Prim (G, d[]) of the vertex and set s) {
     initialization;
     for (n times) {
          u = make D[u] The label of the smallest inaccessible vertex;
          Remember u have been visited;
          For (all vertices that can be reached from u) {
               if (v is not accessed && with u as the intermediary to make V and set S shortest distance d[v] better) {
                    g[u][v] is assigned to the shortest distance of V and set S d[v]} 
          }
}

Specific code implementation: adjacency Matrix version:
const int INF = 1000000000; The/*prim algorithm asks for the minimum spanning tree of the direction-free graph, returns the Benquan of the minimum spanning tree and/or int Prim (int n, int s, vector<vector<int>> G, vector<bool>& Vis                                     , vector<int>& D) {/* param N: Number of vertices s:                                   Initial point G: the adjacency matrix of the graph vis:                                Tag vertex has been accessed D: the shortest distance between the storage vertex and the set S is return:                                        Benquan and/or fill (D.begin (), D.end (), INF) of the minimum spanning tree;                                                             Initialize the shortest distance, all inf d[s] = 0;                                                          The distance between the initial point and the set S is 0 int sum = 0;                                                    Records the Benquan of the minimum spanning tree for (int i = 0; i < n; ++i) {int u =-1;                   U makes d[u] min int min = INF;                              Record minimum d[u] for (int j = 0; J < N; ++j)
                           Start looking for the smallest d[u] {if (vis[j] = = False && D[j] < min) {
                           MIN = D[j];
                     U = j;
              The remaining vertex is not connected to the set S if (U = = 1) return-1 If it is not found d[u with less than INF;                                                  Vis[u] = true;                                                    Mark U for visited sum = D[u]; Adds the smallest edge to the set S distance to the minimum spanning tree for (int v = 0; v < n; ++v) {//v not accessed && You can reach V && with u as a mediation point so that V is closer to set S if (vis[v] = = False && G[u][v]!= INF && G[u][v] & Lt                                    D[V]) D[v] = G[u][v]; Update D[v]}} RetuRN sum; Returns the sum of the Benquan of the minimum spanning tree

adjacency Table Version
const int INF = 1000000000;
       struct Node {int v;
       int dis;

Node (int x, int y): V (x), dis (y) {}};
       int Prim (int n, int s, vector<vector<node>> Adj, vector<bool>& Vis, vector<int>& D) {                     /* param N: Number of vertices s: initial point Adj:                   adjacency table of graphs Vis: Mark Vertex is accessed D: stores the shortest distance from the start S to other vertices return:                                Benquan and/or fill (D.begin (), D.end (), INF) of the minimum spanning tree;                                                     Initialize the shortest distance, all inf d[s] = 0;                                                  The distance between the initial point and the set S is 0 int sum = 0;                                            Records the Benquan of the minimum spanning tree for (int i = 0; i < n; ++i) {int u =-1;                                         U makes d[u] min int min = INF; Record minimum d[u] for (Int J= 0; J < N; ++J)//start looking for the smallest d[u] {if (vis[j] = = False && D[j] ;
                           Min) {min = d[j];
                     U = j;
              The remaining vertex is not connected to the set S if (U = = 1) return-1 If it is not found d[u with less than INF;                                          Vis[u] = true;                                            Mark U for visited sum = D[u]; Adds the smallest edge to the set S distance to the minimum spanning tree for (int j = 0; J < adj[u].size (); ++j) {int V
                     = ADJ[U][J].V;                      if (vis[v] = = False && Adj[u][j].dis < D[V]) d[v] = Adj[u][j].dis;
Update D[v]} return sum; }

The example code on the quiz is as follows:
int main ()
{
	int n = 6;
	/* adjacency Matrix */
	//vector<vector<int>> G = {0,4,inf,inf,1,2},
	//											{4,0,6,inf,inf,3},
	//											{ inf,6,0,6,inf,5},
	//											{inf,inf,6,0,4,5},
	//											{1,inf,inf,4,0,3},
	//											{2,3,5,5,3,0}};

	/* adjacency Table/*
	vector<vector<node>> ADJ = {node (4,1), node (5,2), Node (1,4)},
	{node (0,4), node (5,3), Node (2,6)},
	{node (1,6), node (3,6), Node (5,5)},
	{node (2,6), node (4,4), Node (5,5)},
	{node (0,1), node ( 5,3), node (3,4)},
	{node (0,2), node (1,3), node (2,5), node (3,5), node (4,3)};
	/*for (auto X:adj)
	{for
		(auto y:x)
			cout << y.v<< "-" <<y.dis << "  ;
		cout << Endl;
	} * *
	vector<bool> Vis (n);
	Vector<int> d (n);	int res = Prim (n, 0, G, Vis, d);				Adjacency matrix version
	int res = PRIM1 (n, 0, Adj, Vis, d);		adjacency table version
	cout << res << Endl;

	return 0;
}
The results of the operation are as follows:
Time complexity of O (n^2), only related to the number of vertices in the graph, independent of the number of edges, so the prim algorithm is suitable for Dense diagram

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.