Cod sursa(job #2064337)

Utilizator adireusadireus adireus Data 12 noiembrie 2017 10:57:53
Problema Sortare topologica Scor 100
Compilator c Status done
Runda Arhiva educationala Marime 1.91 kb
#include <stdlib.h>
#include <stdio.h>

struct node {
	int value;
	struct node* next;
};

int list_add (struct node **head, int value)
{
	struct node *tmp;
	//input sanitize
	
	tmp = malloc(sizeof(struct node));
	tmp->value = value;
	tmp->next = *head;
	*head = tmp;
}

int queue_add(struct node **q_head, struct node **q_tail, unsigned int val)
{
	struct node* tmp;
	tmp = malloc(sizeof(struct node));

	tmp->value = val;
	tmp->next = NULL;
	if (*q_head == NULL) {
		*q_head = *q_tail = tmp;
		return 0;
	}
	(*q_tail)->next = tmp;
	*q_tail = tmp;
	return 0;
}

int queue_remove(struct node **q_head, struct node **q_tail, unsigned int* val)
{
	struct node* tmp = *q_head; 
	
	*val = tmp->value;
	*q_head = (*q_head)->next;
	if (*q_head == NULL)
		*q_tail == NULL;
	free(tmp);
}


int queue_is_empty(struct node *q_head, struct node *q_tail)
{
	return (q_head == NULL) ? 1 : 0;
}

int main()
{
	FILE *infile, *outfile;
	unsigned int n, m, i, count = 0;
	struct node **graph;
	unsigned int *inbound;
	struct node *q_head = NULL, *q_tail = NULL;

	infile = fopen("sortaret.in", "r");
	outfile = fopen("sortaret.out", "w");
	//err check
	fscanf(infile, "%u %u", &n, &m);

	graph = malloc((n + 1) * sizeof(struct node*));
	inbound = malloc((n + 1) * sizeof(unsigned int));
	//err check

	for (i = 0; i <=n; i++) {
		graph[i] = NULL;
		inbound[i] = 0;
	}

	for (i = 0; i < m; i++) {
		unsigned int u, v;
		fscanf(infile, "%u %u", &u, &v);
		list_add(&graph[u], v);
		inbound[v]++;
	}

	for (i = 1; i <= n; i++) {
		if (inbound[i] == 0)
			queue_add(&q_head, &q_tail, i);
	}
	
	while (!queue_is_empty (q_head, q_tail)) {
		unsigned int value;
		struct node *tmp;

		queue_remove(&q_head, &q_tail, &value);
		count++;
		fprintf(outfile, "%u ", value);

		for (tmp = graph[value]; tmp != NULL; tmp = tmp->next) {
			inbound[tmp->value]--;
			if(inbound[tmp->value] == 0)
				queue_add(&q_head, &q_tail, tmp->value);
		}
	}
	if (count != n)
		return -1;

	return 0;	
}