3 templates in the prime algorithm
The basic idea of prime algorithm
1. Empty the spanning tree and add a vertex to the spanning tree
2. In those one endpoint in the spanning tree, the other endpoint is not in the edge of the spanning tree, pick one of the least weighted edges and add it to the spanning tree with another endpoint
3. Repeat step 2 until all vertices have entered the spanning tree, at which point the spanning tree is the smallest spanning tree
1. Prime without parameter void Prime (), starting from figure vertex 1 by default
void Prime ()
{
int mincost, index, sum = 0;
for (int i = 0; i < n; i++)
{
Dist[i] = Graph[0][i];
Visit[i] = 0;
}
Visit[0]=1;
for (int i = 0; i < n; i++)
{
Mincost = inf;
for (int j = 0; j<n; j + +)
{
if (visit[j] = = 0 && dist[j] < Mincost)
{
index = j;
Mincost = Dist[j];
}
}
Visit[index] = 1;
sum + = Mincost;
for (int j = 0; J < N; j + +)
{
if (visit[j] = = 0 && dist[j] > Graph[index][j])
DIST[J] = Graph[index][j];
}
}
printf ("%d\n", sum);
}
2. Prime with a parameter int prime (int cur), the parameter is the number of vertices of the graph
int prime (int cur)
{
int index;
int sum = 0;
Memset (visit, false, sizeof (visit));
Visit[cur] = true;
for (int i = 0; I <n; i + +) {
Dist[i] = Graph[cur][i];
}
for (int i = 1; i < n; i + +) {
int mincost = INF;
for (int j = 0; J < N; j + +) {
if (!visit[j] && dist[j] < Mincost) {
Mincost = Dist[j];
index = j;
}
}
Visit[index] = true;
sum + = Mincost;
for (int j = 0; J < m; J + +) {
if (!visit[j] && dist[j] > Graph[index][j]) {
DIST[J] = Graph[index][j];
}
}
}
return sum;
}
3. Prime Band two parameters, int prime (int cost[][101],int num), parameter is the number of vertices of the graph and the two-dimensional adjacency matrix of the graph
int prime (int data[][105],int num)
{
int mincost,index,sum=0;
for (int i=0;i<num;i++)
{
Dist[i]=graph[0][i];
visit[i]=0;
}
Visit[0]=1;
for (int i=1;i<num;i++)
{
Mincost=inf;
for (int j=0;j<num;j++)
if (!visit[j]&&dist[j]<mincost)
{
MINCOST=DIST[J];
Index=j;
}
Visit[index]=1;
Sum+=mincost;
for (int j=0;j<num;j++)
if (Visit[j]==0&&dist[j]>graph[index][j])
DIST[J]=GRAPH[INDEX][J];
}
return sum;
}
The path of algorithm 1_prime