forked from SkienaBooks/Algorithm-Design-Manual-Programs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprim.c
100 lines (75 loc) · 2.33 KB
/
prim.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/* prim.c
Compute minimum spanning trees of graphs via Dijkstra/Prim's algorithm.
by: Steven Skiena
begun: March 6, 2002
*/
/*
Copyright 2003 by Steven S. Skiena; all rights reserved.
Permission is granted for use in non-commerical applications
provided this copyright notice remains intact and unchanged.
This program appears in my book:
"Programming Challenges: The Programming Contest Training Manual"
by Steven Skiena and Miguel Revilla, Springer-Verlag, New York 2003.
See our website www.programming-challenges.com for additional information.
This book can be ordered from Amazon.com at
http://www.amazon.com/exec/obidos/ASIN/0387001638/thealgorithmrepo/
*/
#include <stdio.h>
#include <stdlib.h>
#include "bool.h"
#include "bfs-dfs.h"
#define MAXINT 100007
int parent[MAXV+1]; /* discovery relation */
/************************************************************/
/* [[[ prim_cut */
void prim(graph *g, int start) {
int i; /* counter */
edgenode *p; /* temporary pointer */
bool intree[MAXV+1]; /* is the vertex in the tree yet? */
int distance[MAXV+1];/* cost of adding to tree */
int v; /* current vertex to process */
int w; /* candidate next vertex */
int weight; /* edge weight */
int dist; /* best current distance from start */
for (i = 1; i <= g->nvertices; i++) {
intree[i] = FALSE;
distance[i] = MAXINT;
parent[i] = -1;
}
distance[start] = 0;
v = start;
while (intree[v] == FALSE) {
intree[v] = TRUE;
p = g->edges[v];
while (p != NULL) {
w = p->y;
weight = p->weight;
if ((distance[w] > weight) && (intree[w] == FALSE)) {
distance[w] = weight;
parent[w] = v;
}
p = p->next;
}
v = 1;
dist = MAXINT;
for (i = 1; i <= g->nvertices; i++) {
if ((intree[i] == FALSE) && (dist > distance[i])) {
dist = distance[i];
v = i;
}
}
}
}
/* ]]] */
int main(void) {
graph g;
int i;
read_graph(&g, FALSE);
prim(&g, 1);
printf("Out of Prim\n");
for (i = 1; i <= g.nvertices; i++) {
find_path(1, i, parent);
}
printf("\n");
return 0;
}