Pagini recente » Cod sursa (job #307041) | Cod sursa (job #2453138) | Cod sursa (job #1716149) | Cod sursa (job #499416) | Cod sursa (job #2064337)
#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;
}