[This is my own study notes, welcome reprint, but please specify the source:http://blog.csdn.net/jesson20121020]
Algorithm Description
If the connected graph is a net, the spanning tree with the smallest sum of weights in all spanning trees in the network is the smallest spanning tree, also known as the minimum cost spanning tree. The idea of using the prim algorithm to construct the minimum spanning tree method:
Suppose g= (v,e) is a connected network with n vertices, the vertex set v={v1,v2,..., vn}. The minimum spanning tree t= (U,te) is set, where U is the set of vertices of T, and Te is the edge set of T, and both U and Te initial values are empty.
The basic idea of the prim algorithm is as follows: First take a vertex from V (assuming V1), set the spanning tree to a tree with only one node v1, that is, u={v1}; then as long as U is a true subset of V, in all those one endpoint in T, the other end in the edge outside T, find a shortest (that is, the least weight The Edge. Assuming that the shortest side that meets the criteria is (VI,VJ), The Edge and vertex VJ, which is not in T, are merged into the T's set of TE and vertex sets, respectively. This goes on, merging a vertex and an edge into the spanning tree each time until all the vertices are included in the spanning Tree T. At this point, there must be n-1 in the U=v,te, then t= (u,te) is a minimum spanning tree of G.
Algorithm Implementation
Set up an edge array that records the least expensive edges from the vertex U-set to the V-u, and the information for each edge includes the starting and ending points and weights of the edges. Starting from vertex u, the minimum spanning tree using the prim algorithm is as follows:
(1) Initialize the edge array, recording the vertex u to the least expensive n-1 edge of the remaining nodes in the graph.
(2) Add the vertex u to U.
(3) when u is not equal to V, do the following processing.
1) Select the least expensive edge from the edge array.
2) Add the end of the edge to U.
3) Adjust the edges array so that it always records the least-cost edge of the vertex u to the v-u.
Algorithm Code
Define the edge structure body typedef struct{int start;int end;int cost;} edge;/* *prim Algorithm for minimum spanning tree * */void prim_mg (mgraph Mg,char vs) {Edge Edge[max_vex_num];int i,j,k,v,min;int s = Getindexofvexs (VS,&MG);//Initialize edge for (i = 1;i <= mg.vexnum;i++) {if (s! = i) {Edge[i].start = S;edge[i].end = I;edge[i]. Cost = Mg.arcs[s][i];}} First add s to the spanning tree collection Edge[s].cost = 0;for (i = 2;i <= mg.vexnum;i++) {min = 1000;for (j = 1;j<= mg.vexnum;j++) {if (Edge[j].cos T! = 0 && edge[j].cost < min) {min = Edge[j].cost;k = j;}} v = edge[k].end;edge[v].cost = 0; Join the new node//output The edge printf in the Spanning tree ("%c%c%d\n", Mg.vexs[edge[v].start],mg.vexs[edge[v].end],mg.arcs[edge[v].start][edge[v]. end]);//re-adjust array for (j = 1;j <= mg.vexnum;j++) {if (Edge[j].cost! = 0 && mg.arcs[v][j]! = 0 && Mg.arcs[v][j] < Edge[j].cost) {Edge[j].start = K;edge[j].end = J;edge[j].cost = Mg.arcs[v][j];}}}}
Algorithm Description
Assuming that there are n vertices in the graph, the frequency of the first loop statement that is initialized is N, and the second loop statement has a frequency of n-1. There are two inner loops, one is to find the edge with the least weight in the edge array, the frequency is n-1, the other is to readjust the edge of the edge array, the frequency is N, so the time complexity of the prim algorithm is O (n^2), and it is independent of the number of edges in the graph, so it is suitable for the minimum spanning tree.
Full Code
/* * ===================================================================================== * * FILENAME:PRIM.C * * Description: Prim algorithm of minimum spanning tree algorithm * * version:1.0 * created:2015 March 11 15:27 19 sec * Revision:non E * COMPILER:GCC * * author:jesson20121020 (), [email protected] * Organization: * * ========== =========================================================================== * * #include <stdio.h> #include <stdlib.h> #define Max_vex_num 50#define un_reach 1000typedef char vertextype;typedef enum {DG, UDG} graphtype; typedef struct {Vertextype vexs[max_vex_num];int arcs[max_vex_num][max_vex_num];int vexnum, Arcnum; Graphtype type;} mgraph;/** * Gets the subscript of the specified vertex in the vertex collection by name * Vex Vertex * return if found, returns subscript, otherwise returns 0 */int Getindexofvexs (char vex, mgraph *mg) {int I;FO R (i = 1; I <= mg->vexnum; i++) {if (mg->vexs[i] = = vex) {return i;}} return 0;} /** * Create adjacency Matrix */void create_mg (mgraph *mg) {int I, J, K,weight;int v1, v2, type;chAR C1, c2;printf ("Please input graph type DG (0) or UDG (1):") scanf ("%d", &type); if (type = = 0) Mg->type = Dg;else I F (Type = = 1) Mg->type = udg;else {printf ("Please input correct graph type DG (0) or UDG (1)!"); return;} printf ("Please input Vexmun:"); scanf ("%d", &mg->vexnum);p rintf ("Please input arcnum:"); scanf ("%d", &mg-& Gt;arcnum); GetChar (); for (i = 1; I <= mg->vexnum; i++) {printf ("Please input%dth vex (char):", I); scanf ("%c", &m G->vexs[i]); GetChar ();} Initialize adjacency matrix for (i = 1; I <= mg->vexnum; i++) {for (j = 1; J <= mg->vexnum; J + +) {if (i = = j) Mg->arcs[i][j] = 0 ; elsemg->arcs[i][j] = Un_reach;}} Enter the information for the edge, establish the adjacency matrix for (k = 1; k <= mg->arcnum; k++) {printf ("Please input%dth Arc v1 (char) v2 (char) weight (int):", K) ; scanf ("%c%c%d", &C1, &c2,&weight); v1 = Getindexofvexs (c1, mg); v2 = Getindexofvexs (c2, MG); if (Mg->type = = 1) Mg->arcs[v1][v2] = Mg->arcs[v2][v1] = Weight;elsemg->arcs[v1][v2] = Weight;getchar ();}} /** * Print adjacency matrix and vertex information */void print_mg (mgraph MG) {int I, j;if (mg.type = = DG) {printf ("Graph type:direct graph\n");} else{printf ("Graph type:undirect graph\n");} printf ("Graph vertex number:%d\n", Mg.vexnum);p rintf ("graph arc Number:%d\n", Mg.arcnum);p rintf ("Vertex set:\n"); for ( i = 1; I <= mg.vexnum; i++) printf ("%c\t", Mg.vexs[i]);p rintf ("\nadjacency matrix:\n"); for (i = 1; I <= mg.vexnum; i++) {j = 1;for (; J < MG . Vexnum; J + +) {printf ("%d\t", Mg.arcs[i][j]);} printf ("%d\n", Mg.arcs[i][j]);}} Define the edge structure body typedef struct{int start;int end;int cost;} edge;/* *prim algorithm for minimum spanning tree * */void prim_mg (mgraph Mg,char vs) {Edge Edge[max_vex_num];int i,j,k,v,min;int s = Getindexofvexs (v S,&MG);//Initialize edge for (i = 1;i <= mg.vexnum;i++) {if (s! = i) {Edge[i].start = S;edge[i].end = I;edge[i].cost = Mg.arcs[s][i ];}} First add s to the spanning tree collection Edge[s].cost = 0;for (i = 2;i <= mg.vexnum;i++) {min = 1000;for (j = 1;j<= mg.vexnum;j++) {if (Edge[j].cos T! = 0 && edge[j].cost < min) {min = Edge[j].cost;k = j;}} v = edge[k].enD;edge[v].cost = 0; Join the new node//output The edge printf in the Spanning tree ("%c%c%d\n", Mg.vexs[edge[v].start],mg.vexs[edge[v].end],mg.arcs[edge[v].start][edge[v]. end]);//re-adjust array for (j = 1;j <= mg.vexnum;j++) {if (Edge[j].cost! = 0 && mg.arcs[v][j]! = 0 && Mg.arcs[v][j] < Edge[j].cost) {Edge[j].start = K;edge[j].end = J;edge[j].cost = Mg.arcs[v][j];}}}} /** * Main function */int main (void) {mgraph Mg;char startvex;create_mg (&mg);p rint_mg (MG);p rintf ("\nplease input the start vex ( char): "); scanf ("%c ", &startvex);p rintf (" \nthe result of prim:\n "); PRIM_MG (Mg,startvex); return exit_success;}
Run the demo
[Email protected]:~/develop/workspace/c_learning/csdn/prim$ gcc-o Prim prim.c[email protected]:~/develop/workspace/ c_learning/csdn/prim$./prim Please input graph type DG (0) or UDG (1): 1Please input Vexmun:4please input Arcnum:5pleas E input 1th vex (char): aplease input 2th vex (char): bplease input 3th vex (char): cplease input 4th vex (char):d please input 1t H Arc v1 (char) v2 (char) weight (int): A b 1Please input 2th Arc v1 (char) v2 (char) weight (int): A c 3Please input 3th arc v1 (char) v2 (char) weight (int): A D 4Please input 4th Arc v1 (char) v2 (char) weight (int): b C 2Please input 5th Arc v1 (char) v 2 (char) weight (int): C d 3Please input the start vex (char): athe result of PRIM:A B 1b C 2c d 3
Data structure (c implementation)-------Prim algorithm of minimum spanning tree