Home | History | Annotate | Line # | Download | only in tsort
tsort.c revision 1.3
      1  1.1      cgd /*
      2  1.1      cgd  * Copyright (c) 1989 The Regents of the University of California.
      3  1.1      cgd  * All rights reserved.
      4  1.1      cgd  *
      5  1.1      cgd  * This code is derived from software contributed to Berkeley by
      6  1.1      cgd  * Michael Rendell of Memorial University of Newfoundland.
      7  1.1      cgd  *
      8  1.1      cgd  * Redistribution and use in source and binary forms, with or without
      9  1.1      cgd  * modification, are permitted provided that the following conditions
     10  1.1      cgd  * are met:
     11  1.1      cgd  * 1. Redistributions of source code must retain the above copyright
     12  1.1      cgd  *    notice, this list of conditions and the following disclaimer.
     13  1.1      cgd  * 2. Redistributions in binary form must reproduce the above copyright
     14  1.1      cgd  *    notice, this list of conditions and the following disclaimer in the
     15  1.1      cgd  *    documentation and/or other materials provided with the distribution.
     16  1.1      cgd  * 3. All advertising materials mentioning features or use of this software
     17  1.1      cgd  *    must display the following acknowledgement:
     18  1.1      cgd  *	This product includes software developed by the University of
     19  1.1      cgd  *	California, Berkeley and its contributors.
     20  1.1      cgd  * 4. Neither the name of the University nor the names of its contributors
     21  1.1      cgd  *    may be used to endorse or promote products derived from this software
     22  1.1      cgd  *    without specific prior written permission.
     23  1.1      cgd  *
     24  1.1      cgd  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     25  1.1      cgd  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     26  1.1      cgd  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     27  1.1      cgd  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     28  1.1      cgd  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     29  1.1      cgd  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     30  1.1      cgd  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     31  1.1      cgd  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     32  1.1      cgd  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     33  1.1      cgd  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     34  1.1      cgd  * SUCH DAMAGE.
     35  1.1      cgd  */
     36  1.1      cgd 
     37  1.1      cgd #ifndef lint
     38  1.1      cgd char copyright[] =
     39  1.1      cgd "@(#) Copyright (c) 1989 The Regents of the University of California.\n\
     40  1.1      cgd  All rights reserved.\n";
     41  1.1      cgd #endif /* not lint */
     42  1.1      cgd 
     43  1.1      cgd #ifndef lint
     44  1.2  mycroft /*static char sccsid[] = "from: @(#)tsort.c	5.3 (Berkeley) 6/1/90";*/
     45  1.3      cgd static char rcsid[] = "$Id: tsort.c,v 1.3 1993/11/17 12:01:04 cgd Exp $";
     46  1.1      cgd #endif /* not lint */
     47  1.1      cgd 
     48  1.1      cgd #include <sys/types.h>
     49  1.1      cgd #include <errno.h>
     50  1.1      cgd #include <stdio.h>
     51  1.1      cgd #include <ctype.h>
     52  1.1      cgd #include <string.h>
     53  1.1      cgd 
     54  1.1      cgd /*
     55  1.1      cgd  *  Topological sort.  Input is a list of pairs of strings seperated by
     56  1.1      cgd  *  white space (spaces, tabs, and/or newlines); strings are written to
     57  1.1      cgd  *  standard output in sorted order, one per line.
     58  1.1      cgd  *
     59  1.1      cgd  *  usage:
     60  1.1      cgd  *     tsort [inputfile]
     61  1.1      cgd  *  If no input file is specified, standard input is read.
     62  1.1      cgd  *
     63  1.1      cgd  *  Should be compatable with AT&T tsort HOWEVER the output is not identical
     64  1.1      cgd  *  (i.e. for most graphs there is more than one sorted order, and this tsort
     65  1.1      cgd  *  usually generates a different one then the AT&T tsort).  Also, cycle
     66  1.1      cgd  *  reporting seems to be more accurate in this version (the AT&T tsort
     67  1.1      cgd  *  sometimes says a node is in a cycle when it isn't).
     68  1.1      cgd  *
     69  1.1      cgd  *  Michael Rendell, michael (at) stretch.cs.mun.ca - Feb 26, '90
     70  1.1      cgd  */
     71  1.1      cgd #define	HASHSIZE	53		/* doesn't need to be big */
     72  1.1      cgd #define	NF_MARK		0x1		/* marker for cycle detection */
     73  1.1      cgd #define	NF_ACYCLIC	0x2		/* this node is cycle free */
     74  1.1      cgd 
     75  1.1      cgd typedef struct node_str NODE;
     76  1.1      cgd 
     77  1.1      cgd struct node_str {
     78  1.1      cgd 	char *n_name;			/* name of this node */
     79  1.1      cgd 	NODE **n_prevp;			/* pointer to previous node's n_next */
     80  1.1      cgd 	NODE *n_next;			/* next node in graph */
     81  1.1      cgd 	NODE *n_hash;			/* next node in hash table */
     82  1.1      cgd 	int n_narcs;			/* number of arcs in n_arcs[] */
     83  1.1      cgd 	int n_arcsize;			/* size of n_arcs[] array */
     84  1.1      cgd 	NODE **n_arcs;			/* array of arcs to other nodes */
     85  1.1      cgd 	int n_refcnt;			/* # of arcs pointing to this node */
     86  1.1      cgd 	int n_flags;			/* NF_* */
     87  1.1      cgd };
     88  1.1      cgd 
     89  1.1      cgd typedef struct _buf {
     90  1.1      cgd 	char *b_buf;
     91  1.1      cgd 	int b_bsize;
     92  1.1      cgd } BUF;
     93  1.1      cgd 
     94  1.1      cgd NODE *add_node(), *find_node();
     95  1.1      cgd void add_arc(), no_memory(), remove_node(), tsort();
     96  1.1      cgd char *grow_buf(), *malloc();
     97  1.1      cgd 
     98  1.1      cgd extern int errno;
     99  1.1      cgd NODE *graph;
    100  1.1      cgd NODE *hashtable[HASHSIZE];
    101  1.1      cgd NODE **cycle_buf;
    102  1.1      cgd NODE **longest_cycle;
    103  1.1      cgd 
    104  1.1      cgd main(argc, argv)
    105  1.1      cgd 	int argc;
    106  1.1      cgd 	char **argv;
    107  1.1      cgd {
    108  1.1      cgd 	register BUF *b;
    109  1.1      cgd 	register int c, n;
    110  1.1      cgd 	FILE *fp;
    111  1.1      cgd 	int bsize, nused;
    112  1.1      cgd 	BUF bufs[2];
    113  1.1      cgd 
    114  1.1      cgd 	if (argc < 2)
    115  1.1      cgd 		fp = stdin;
    116  1.1      cgd 	else if (argc == 2) {
    117  1.1      cgd 		(void)fprintf(stderr, "usage: tsort [ inputfile ]\n");
    118  1.1      cgd 		exit(1);
    119  1.1      cgd 	} else if (!(fp = fopen(argv[1], "r"))) {
    120  1.1      cgd 		(void)fprintf(stderr, "tsort: %s.\n", strerror(errno));
    121  1.1      cgd 		exit(1);
    122  1.1      cgd 	}
    123  1.1      cgd 
    124  1.1      cgd 	for (b = bufs, n = 2; --n >= 0; b++)
    125  1.1      cgd 		b->b_buf = grow_buf((char *)NULL, b->b_bsize = 1024);
    126  1.1      cgd 
    127  1.1      cgd 	/* parse input and build the graph */
    128  1.1      cgd 	for (n = 0, c = getc(fp);;) {
    129  1.1      cgd 		while (c != EOF && isspace(c))
    130  1.1      cgd 			c = getc(fp);
    131  1.1      cgd 		if (c == EOF)
    132  1.1      cgd 			break;
    133  1.1      cgd 
    134  1.1      cgd 		nused = 0;
    135  1.1      cgd 		b = &bufs[n];
    136  1.1      cgd 		bsize = b->b_bsize;
    137  1.1      cgd 		do {
    138  1.1      cgd 			b->b_buf[nused++] = c;
    139  1.1      cgd 			if (nused == bsize) {
    140  1.1      cgd 				bsize *= 2;
    141  1.1      cgd 				b->b_buf = grow_buf(b->b_buf, bsize);
    142  1.1      cgd 			}
    143  1.1      cgd 			c = getc(fp);
    144  1.1      cgd 		} while (c != EOF && !isspace(c));
    145  1.1      cgd 
    146  1.1      cgd 		b->b_buf[nused] = '\0';
    147  1.1      cgd 		b->b_bsize = bsize;
    148  1.1      cgd 		if (n)
    149  1.1      cgd 			add_arc(bufs[0].b_buf, bufs[1].b_buf);
    150  1.1      cgd 		n = !n;
    151  1.1      cgd 	}
    152  1.1      cgd 	(void)fclose(fp);
    153  1.1      cgd 	if (n) {
    154  1.1      cgd 		(void)fprintf(stderr, "tsort: odd data count.\n");
    155  1.1      cgd 		exit(1);
    156  1.1      cgd 	}
    157  1.1      cgd 
    158  1.1      cgd 	/* do the sort */
    159  1.1      cgd 	tsort();
    160  1.1      cgd 	exit(0);
    161  1.1      cgd }
    162  1.1      cgd 
    163  1.1      cgd /* double the size of oldbuf and return a pointer to the new buffer. */
    164  1.1      cgd char *
    165  1.1      cgd grow_buf(bp, size)
    166  1.1      cgd 	char *bp;
    167  1.1      cgd 	int size;
    168  1.1      cgd {
    169  1.1      cgd 	char *realloc();
    170  1.1      cgd 
    171  1.1      cgd 	if (!(bp = realloc(bp, (u_int)size)))
    172  1.1      cgd 		no_memory();
    173  1.1      cgd 	return(bp);
    174  1.1      cgd }
    175  1.1      cgd 
    176  1.1      cgd /*
    177  1.1      cgd  * add an arc from node s1 to node s2 in the graph.  If s1 or s2 are not in
    178  1.1      cgd  * the graph, then add them.
    179  1.1      cgd  */
    180  1.1      cgd void
    181  1.1      cgd add_arc(s1, s2)
    182  1.1      cgd 	char *s1, *s2;
    183  1.1      cgd {
    184  1.1      cgd 	register NODE *n1;
    185  1.1      cgd 	NODE *n2;
    186  1.1      cgd 	int bsize;
    187  1.1      cgd 
    188  1.1      cgd 	n1 = find_node(s1);
    189  1.1      cgd 	if (!n1)
    190  1.1      cgd 		n1 = add_node(s1);
    191  1.1      cgd 
    192  1.1      cgd 	if (!strcmp(s1, s2))
    193  1.1      cgd 		return;
    194  1.1      cgd 
    195  1.1      cgd 	n2 = find_node(s2);
    196  1.1      cgd 	if (!n2)
    197  1.1      cgd 		n2 = add_node(s2);
    198  1.1      cgd 
    199  1.1      cgd 	/*
    200  1.3      cgd 	 * Check if this arc is already here.
    201  1.3      cgd 	 */
    202  1.3      cgd 	for (i = 0; i < n1->n_narcs; i++)
    203  1.3      cgd 		if (n1->n_arcs[i] == n2)
    204  1.3      cgd 			return;
    205  1.3      cgd 
    206  1.3      cgd 	/*
    207  1.3      cgd 	 * Add it.
    208  1.1      cgd 	 */
    209  1.1      cgd 	if (n1->n_narcs == n1->n_arcsize) {
    210  1.1      cgd 		if (!n1->n_arcsize)
    211  1.1      cgd 			n1->n_arcsize = 10;
    212  1.1      cgd 		bsize = n1->n_arcsize * sizeof(*n1->n_arcs) * 2;
    213  1.1      cgd 		n1->n_arcs = (NODE **)grow_buf((char *)n1->n_arcs, bsize);
    214  1.1      cgd 		n1->n_arcsize = bsize / sizeof(*n1->n_arcs);
    215  1.1      cgd 	}
    216  1.1      cgd 	n1->n_arcs[n1->n_narcs++] = n2;
    217  1.1      cgd 	++n2->n_refcnt;
    218  1.1      cgd }
    219  1.1      cgd 
    220  1.1      cgd hash_string(s)
    221  1.1      cgd 	char *s;
    222  1.1      cgd {
    223  1.1      cgd 	register int hash, i;
    224  1.1      cgd 
    225  1.1      cgd 	for (hash = 0, i = 1; *s; s++, i++)
    226  1.1      cgd 		hash += *s * i;
    227  1.1      cgd 	return(hash % HASHSIZE);
    228  1.1      cgd }
    229  1.1      cgd 
    230  1.1      cgd /*
    231  1.1      cgd  * find a node in the graph and return a pointer to it - returns null if not
    232  1.1      cgd  * found.
    233  1.1      cgd  */
    234  1.1      cgd NODE *
    235  1.1      cgd find_node(name)
    236  1.1      cgd 	char *name;
    237  1.1      cgd {
    238  1.1      cgd 	register NODE *n;
    239  1.1      cgd 
    240  1.1      cgd 	for (n = hashtable[hash_string(name)]; n; n = n->n_hash)
    241  1.1      cgd 		if (!strcmp(n->n_name, name))
    242  1.1      cgd 			return(n);
    243  1.1      cgd 	return((NODE *)NULL);
    244  1.1      cgd }
    245  1.1      cgd 
    246  1.1      cgd /* Add a node to the graph and return a pointer to it. */
    247  1.1      cgd NODE *
    248  1.1      cgd add_node(name)
    249  1.1      cgd 	char *name;
    250  1.1      cgd {
    251  1.1      cgd 	register NODE *n;
    252  1.1      cgd 	int hash;
    253  1.1      cgd 
    254  1.1      cgd 	if (!(n = (NODE *)malloc(sizeof(NODE))) || !(n->n_name = strdup(name)))
    255  1.1      cgd 		no_memory();
    256  1.1      cgd 
    257  1.1      cgd 	n->n_narcs = 0;
    258  1.1      cgd 	n->n_arcsize = 0;
    259  1.1      cgd 	n->n_arcs = (NODE **)NULL;
    260  1.1      cgd 	n->n_refcnt = 0;
    261  1.1      cgd 	n->n_flags = 0;
    262  1.1      cgd 
    263  1.1      cgd 	/* add to linked list */
    264  1.1      cgd 	if (n->n_next = graph)
    265  1.1      cgd 		graph->n_prevp = &n->n_next;
    266  1.1      cgd 	n->n_prevp = &graph;
    267  1.1      cgd 	graph = n;
    268  1.1      cgd 
    269  1.1      cgd 	/* add to hash table */
    270  1.1      cgd 	hash = hash_string(name);
    271  1.1      cgd 	n->n_hash = hashtable[hash];
    272  1.1      cgd 	hashtable[hash] = n;
    273  1.1      cgd 	return(n);
    274  1.1      cgd }
    275  1.1      cgd 
    276  1.1      cgd /* do topological sort on graph */
    277  1.1      cgd void
    278  1.1      cgd tsort()
    279  1.1      cgd {
    280  1.1      cgd 	register NODE *n, *next;
    281  1.1      cgd 	register int cnt;
    282  1.1      cgd 
    283  1.1      cgd 	while (graph) {
    284  1.1      cgd 		/*
    285  1.1      cgd 		 * keep getting rid of simple cases until there are none left,
    286  1.1      cgd 		 * if there are any nodes still in the graph, then there is
    287  1.1      cgd 		 * a cycle in it.
    288  1.1      cgd 		 */
    289  1.1      cgd 		do {
    290  1.1      cgd 			for (cnt = 0, n = graph; n; n = next) {
    291  1.1      cgd 				next = n->n_next;
    292  1.1      cgd 				if (n->n_refcnt == 0) {
    293  1.1      cgd 					remove_node(n);
    294  1.1      cgd 					++cnt;
    295  1.1      cgd 				}
    296  1.1      cgd 			}
    297  1.1      cgd 		} while (graph && cnt);
    298  1.1      cgd 
    299  1.1      cgd 		if (!graph)
    300  1.1      cgd 			break;
    301  1.1      cgd 
    302  1.1      cgd 		if (!cycle_buf) {
    303  1.1      cgd 			/*
    304  1.1      cgd 			 * allocate space for two cycle logs - one to be used
    305  1.1      cgd 			 * as scratch space, the other to save the longest
    306  1.1      cgd 			 * cycle.
    307  1.1      cgd 			 */
    308  1.1      cgd 			for (cnt = 0, n = graph; n; n = n->n_next)
    309  1.1      cgd 				++cnt;
    310  1.1      cgd 			cycle_buf =
    311  1.1      cgd 			    (NODE **)malloc((u_int)sizeof(NODE *) * cnt);
    312  1.1      cgd 			longest_cycle =
    313  1.1      cgd 			    (NODE **)malloc((u_int)sizeof(NODE *) * cnt);
    314  1.1      cgd 			if (!cycle_buf || !longest_cycle)
    315  1.1      cgd 				no_memory();
    316  1.1      cgd 		}
    317  1.1      cgd 		for (n = graph; n; n = n->n_next)
    318  1.1      cgd 			if (!(n->n_flags & NF_ACYCLIC)) {
    319  1.1      cgd 				if (cnt = find_cycle(n, n, 0, 0)) {
    320  1.1      cgd 					register int i;
    321  1.1      cgd 
    322  1.1      cgd 					(void)fprintf(stderr,
    323  1.1      cgd 					    "tsort: cycle in data.\n");
    324  1.1      cgd 					for (i = 0; i < cnt; i++)
    325  1.1      cgd 						(void)fprintf(stderr,
    326  1.1      cgd 				"tsort: %s.\n", longest_cycle[i]->n_name);
    327  1.1      cgd 					remove_node(n);
    328  1.1      cgd 					break;
    329  1.1      cgd 				} else
    330  1.1      cgd 					/* to avoid further checks */
    331  1.1      cgd 					n->n_flags  = NF_ACYCLIC;
    332  1.1      cgd 			}
    333  1.1      cgd 
    334  1.1      cgd 		if (!n) {
    335  1.1      cgd 			(void)fprintf(stderr,
    336  1.1      cgd 			    "tsort: internal error -- could not find cycle.\n");
    337  1.1      cgd 			exit(1);
    338  1.1      cgd 		}
    339  1.1      cgd 	}
    340  1.1      cgd }
    341  1.1      cgd 
    342  1.1      cgd /* print node and remove from graph (does not actually free node) */
    343  1.1      cgd void
    344  1.1      cgd remove_node(n)
    345  1.1      cgd 	register NODE *n;
    346  1.1      cgd {
    347  1.1      cgd 	register NODE **np;
    348  1.1      cgd 	register int i;
    349  1.1      cgd 
    350  1.1      cgd 	(void)printf("%s\n", n->n_name);
    351  1.1      cgd 	for (np = n->n_arcs, i = n->n_narcs; --i >= 0; np++)
    352  1.1      cgd 		--(*np)->n_refcnt;
    353  1.1      cgd 	n->n_narcs = 0;
    354  1.1      cgd 	*n->n_prevp = n->n_next;
    355  1.1      cgd 	if (n->n_next)
    356  1.1      cgd 		n->n_next->n_prevp = n->n_prevp;
    357  1.1      cgd }
    358  1.1      cgd 
    359  1.1      cgd /* look for the longest cycle from node from to node to. */
    360  1.1      cgd find_cycle(from, to, longest_len, depth)
    361  1.1      cgd 	NODE *from, *to;
    362  1.1      cgd 	int depth, longest_len;
    363  1.1      cgd {
    364  1.1      cgd 	register NODE **np;
    365  1.1      cgd 	register int i, len;
    366  1.1      cgd 
    367  1.1      cgd 	/*
    368  1.1      cgd 	 * avoid infinite loops and ignore portions of the graph known
    369  1.1      cgd 	 * to be acyclic
    370  1.1      cgd 	 */
    371  1.1      cgd 	if (from->n_flags & (NF_MARK|NF_ACYCLIC))
    372  1.1      cgd 		return(0);
    373  1.1      cgd 	from->n_flags = NF_MARK;
    374  1.1      cgd 
    375  1.1      cgd 	for (np = from->n_arcs, i = from->n_narcs; --i >= 0; np++) {
    376  1.1      cgd 		cycle_buf[depth] = *np;
    377  1.1      cgd 		if (*np == to) {
    378  1.1      cgd 			if (depth + 1 > longest_len) {
    379  1.1      cgd 				longest_len = depth + 1;
    380  1.1      cgd 				(void)memcpy((char *)longest_cycle,
    381  1.1      cgd 				    (char *)cycle_buf,
    382  1.1      cgd 				    longest_len * sizeof(NODE *));
    383  1.1      cgd 			}
    384  1.1      cgd 		} else {
    385  1.1      cgd 			len = find_cycle(*np, to, longest_len, depth + 1);
    386  1.1      cgd 			if (len > longest_len)
    387  1.1      cgd 				longest_len = len;
    388  1.1      cgd 		}
    389  1.1      cgd 	}
    390  1.1      cgd 	from->n_flags &= ~NF_MARK;
    391  1.1      cgd 	return(longest_len);
    392  1.1      cgd }
    393  1.1      cgd 
    394  1.1      cgd void
    395  1.1      cgd no_memory()
    396  1.1      cgd {
    397  1.1      cgd 	(void)fprintf(stderr, "tsort: %s.\n", strerror(ENOMEM));
    398  1.1      cgd 	exit(1);
    399  1.1      cgd }
    400