Link: Click to open link
The subject of another algorithm (prime algorithm) algorithm is to use a two-dimensional array map of its subscript, respectively, the two villages connected to the label, the content is the length of the road, that is, the weight value. Using a mark Array to mark a connected village, a one-dimensional array lowcost is stored as the weight of the end of the following, some of which are connected no longer need to be constructed, and the value of the corresponding map array is labeled 0 (one path corresponds to two map). For details, see the code:
#include <stdio.h> #include <string.h> #define INF 0xffffffint map[110][110];int mark[110],lowcost[110]; void prime (int n) {int sum=0;memset (mark,0,sizeof (Mark)); for (int i=1;i<=n;i++) lowcost[i]=map[1][i];mark[1]=1; lowcost[1]=0;for (int i=1;i<n;i++)//There are n villages, it is necessary to find n-1 times {int vir,min=inf;for (int j=1;j<=n;j++)//Traverse all points to find the point with the least weight, Record its subscript {if (!mark[j]&&lowcost[j]<min) {min=lowcost[j];vir=j;}} The mark[vir]=1;//will sum+=lowcost[vir];//the weighted value for this minimum spanning tree for (int k=1;k<=n;k++) with the found tag,//Update the non-fetching point to the weighted if (!mark[k]&& LOWCOST[K]>MAP[VIR][K]) lowcost[k]=map[vir][k];} printf ("%d\n", sum);} int main () {int n,m;while (scanf ("%d", &n)!=eof) {memset (map,inf,sizeof (map));//initialize diagram to infinity for (int i=1;i<=n;i++) for (int j=1;j<=n;j++) scanf ("%d", &map[i][j]);//input Graph scanf ("%d", &m), int x,y;while (m--) {scanf ("%d%d",& X,&y) map[x][y]=map[y][x]=0;//to mark the repaired road weight as 0}prime (n);} return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
HDU 1102 Constructing Roads (prime algorithm)