# Prim algorithm (minimum spanning tree)

prim algorithm realizes the minimum spanning tree of graph, assuming n vertices and m edges.

The time complexity of kruskal algorithm is O(eloge), which is related to the number of edges. It is suitable for sparse graphs.

Algorithm idea: starting from a vertex, suppose v0, at this time v0 belongs to an element of the minimum spanning tree node, suppose u is the set of points that have been determined as the spanning tree, and the remaining V-U is the set of points to be determined. At this time, select the point in V-U that has the smallest path to the point in U, which is the new edge of the spanning tree, and add the selected points to u until u is included in the figure It's all up to the point.

The algorithm needs to be optimized when selecting the minimum path. The specific idea is: w [] array saves the shortest path of each vertex, b [] array saves the shortest path of i vertex, for example, the shortest path to vertex 0 is < V0, V3 >, then w [0] = e < V0, V3 >, b[0]=3; thus, finding the minimum path every time is not the cost of o(n*n).

The coding process and Dijkstra Very similar, but the meaning of the dis array has changed. (Dijkstra is the shortest distance from the source point to other points, Prim is the shortest distance from the points in the current set of spanning tree points to other points)

```#include <iostream>
using namespace std;
const int inf = 0x3f3f3f3f;
int edge[5][5] =
{
{ -1,-1,-1,-1,-1 },
{ -1, 0, 2, 6, 4 },
{ -1, inf, 0,3, inf },
{ -1, 7, inf, 0, 1 },
{ -1, 5, inf, 12, 0 }
};

int main() {
const int n = 4;//Number of points
int dis[n + 1];//The shortest distance from the current set of spanning tree points to the remaining points
int book[n + 1];//Is the minimum value from each point to the source point
int b[n + 1];//Set of edge of spanning tree (edge is < I, B [i] >
//Initialization, set source point to n1
for (int i = 1; i <= n; ++i)
dis[i] = edge[1][i];

//book array initialization
memset(book, 0, sizeof(book));
//Initialization, each point points to 1;
for (int i = 1; i <= n; ++i)
b[i] = 1;

book[1] = 1;

int min;//Currently, the minimum distance from the shortest path point to the source point is not determined
//Prim algorithm core statement
for (int i = 1; i <= n - 1; ++i) {
//Find the closest vertex to vertex 1
min = inf;
int u;
for (int j = 1; j <= n; ++j) {
if (book[j] == 0 && dis[j] < min) {
min = dis[j];
u = j;
}
}
//Each iteration can determine a shortest distance, so as long as iteration n-1
book[u] = 1;
//Update the dis array through the determined points
//(undetermined points reduce the distance to points in the spanning tree set through point u)
for (int v = 1; v <= n; ++v) {
if (edge[u][v] < inf) {
if (!book[v] && dis[v] > edge[u][v]) {
dis[v] = edge[u][v];
b[v] = u;
}
}
}
}
//Output result
for (int i = 1; i <= n; ++i)
cout << b[i] << ", " << i << endl;
system("pause");
return 0;
}```

Posted by justinjkiss on Sun, 10 Nov 2019 12:22:33 -0800