Professional Documents
Culture Documents
/*
The input file (dist.txt) look something like this
4
0 0 0 21
0 0 8 17
0 8 0 16
21 17 16 0
#include "stdio.h"
int n; /* The number of nodes in the graph */
int weight[100][100]; /* weight[i][j] is the distance between node i and node j;
if there is no path between i and j, weight[i][j] should
be 0 */
char inTree[100]; /* inTree[i] is 1 if the node i is already in the minimum
spanning tree; 0 otherwise*/
int d[100]; /* d[i] is the distance between node i and the minimum
spanning tree; this is initially infinity (100000); if i is already in
the tree, then d[i] is undefined; this is just a temporary variable.
It's not necessary but speeds up execution considerably (by a
factor of n) */
int whoTo[100]; /* whoTo[i] holds the index of the node i would have to be
linked to in order to get a distance of d[i] */
main()
{
FILE *f = fopen("dist.txt", "r");
int i,j,total,treeSize;
fscanf(f, "%d", &n);
for (i = 0; i < n; ++i)
for (j = 0; j < n; ++j)
fscanf(f, "%d", &weight[i][j]);
fclose(f);
/* And add it */
printf("Adding edge %c-%c\n", whoTo[min] + 'A', min + 'A');
inTree[min] = 1;
total += d[min];
updateDistances(min);
}
return 0;
}
Prim(G, w, s)
//Input: undirected connected weighted graph G = (V,E) in adj list representation,
source vertex s in V
//Output: p[1..|V|], representing the set of edges composing an MST of G
01 for each v in V
02 color(v) <- WHITE
03 key(v) <- infinity
04 p(v) <- NIL
05 Q <- empty list // Q keyed by key[v]
06 color(s) <- GRAY
07 Insert(Q, s)
08 key(s) <- 0
09 while Q != empty
10 u <- Extract-Min(Q)
11 for v in Adj[u]
12 if color(v) = WHITE
13 then color(v) <- GRAY
14 Insert(Q,v)
15 key(v) <- w(u,v)
16 p(v) <- u
17 elseif color(v) = GRAY
18 then if key(v) > w(u,v)
19 then key(v) <- w(u,v)
20 p(v) <- u
21 color(v) <- BLACK
22 return(p)
Prim’s Algorithm