Copy Code code as follows:
#include <iostream.h>
#define MAX 100
#define MAXCOST 100000
int Graph[max][max];
int Prim (int graph[max][max], int n)
{
/* Lowcost[i] records the minimum weight of an edge at the end of I, when the lowcost[i]=0 indicates the end I join the spanning tree * *
int Lowcost[max];
/* Mst[i] record corresponds to the starting point of lowcost[i] * *
int Mst[max];
int I, J, Min, minid, sum = 0;
/* Default selection of node No. 0 to join the build tree, starting from node 1th to initialize the * *
for (i = 1; i < n; i++)
{
/* The shortest distance is initialized to the distance from the other node to the NO. 0 node * *
Lowcost[i] = Graph[0][i];
/* Mark the starting point of all nodes is the default No. No. 0 Node * *
Mst[i] = 0;
}
/* Tag No. 0 node to join the spanning tree * *
Lowcost[0] = 0;
/* N nodes need at least n-1 to make minimum spanning tree
for (i = 1; i < n; i++)
{
min = maxcost;
MiniD = 0;
/* Find the node with the minimum weight value of the condition MiniD * *
For (J =1 J <n; J + +)
{
/* Edge weights are small and not in the spanning tree.
if (Lowcost[j] < min && Lowcost[j]!= 0)
{
min = Lowcost[j];
MiniD = j;
}
}
/* Output to generate tree edge information: Starting point, end point, weight * *
cout<< "The starting point, end point and weight value of the generation of several edges are:" << mst[minid]+1<< "" <<minid+1<< "" <<min<<endl;
/* Cumulative Weight value * *
sum = min;
/* Tag node MiniD join the Spanning tree * *
Lowcost[minid] = 0;
/* Update the value of the current node MiniD to the other node * *
for (j = 1; j < N; j + +)
{
* * Find a smaller weight value * *
if (Graph[minid][j] < lowcost[j])
{
/* Update weight information * *
LOWCOST[J] = Graph[minid][j];
/* Update the minimum weight edge of the starting point * *
MST[J] = MiniD;
}
}
}
/* Returns the minimum weight and * *
return sum;
}
void Main ()
{
int I, j, M,n;
int cost;
/* Number of READ nodes * *
cout<< "Please enter the number of nodes in this graph:";
cin>>m;
/* initialization diagram, the distance between all nodes is infinity * *
for (i = 0; I <m; i++)
{
For (J =i+1 J <m; J + +)
{
cout<< "Please enter the node" <<i+1<< "to the node" <<j+1<< "Edge of the weight, if the infinite input maxcost (100000):";
cin>>n;
GRAPH[I][J] = n;
Graph[j][i] = n;
}
Graph[i][i]=maxcost;
}
/* Solve the minimum spanning tree * *
Cost = Prim (graph, M);
cout<< the weight of the minimum spanning tree is: <<cost<<endl;
}