#include <stdio.h>
#include <stdlib.h>
struct list
{
int info;
struct list *next;
};
typedef struct list List;
void push(int value, List *stackTop);
int pop(List *stackTop);
int read(List **graph, const char *fileName);
void df(int current, int *visited, List **graph, List *stack, List *solution);
void topologicalSort(List **graph, int nrVertices, List *solution);
int main()
{
FILE *out = fopen("sortaret.out", "w");
List **graph, *solution;
int nrVertices;
solution = malloc(sizeof(List));
nrVertices = read(graph, "sortaret.in");
topologicalSort(graph, nrVertices, solution);
for(solution = solution->next; solution; solution = solution->next)
fprintf(out, "%d ", solution->info);
fprintf(out, "\n");
fclose(out);
return 0;
}
void topologicalSort(List **graph, int nrVertices, List *solution)
{
int *visited, i;
List *stack;
stack = malloc(sizeof(List));
visited = calloc(nrVertices + 1, sizeof(int));
stack->next = solution->next = NULL;
for(i = 1; i <= nrVertices; i++)
if(!visited[i])
{
df(i, visited, graph, stack, solution);
push(i, solution);
}
}
void df(int current, int *visited, List **graph, List *stack, List *solution)
{
List *c;
visited[current] = 1;
for(c = graph[current]; c; c = c->next)
if(!visited[c->info])
{
push(c->info, stack);
df(c->info, visited, graph, stack, solution);
push(pop(stack), solution);
}
}
int read(List **graph, const char *fileName)
{
FILE *in = fopen(fileName, "r");
List *v;
int m, n, i;
fscanf(in, "%d %d", &n, &m);
*graph = malloc((n + 1) * sizeof(List));
for(i = 0; i <= n; i++) graph[i] = NULL;
for(; m ; m--)
{
int a, b;
fscanf(in, "%d %d", &a, &b);
v = malloc(sizeof(List));
v->info = b;
v->next = graph[a];
graph[a] = v;
}
fclose(in);
return n;
}
void push(int value, List *stackTop)
{
List *c;
c = malloc(sizeof(List));
c->info = value;
c->next = stackTop->next;
stackTop->next = c;
}
int pop(List *stackTop)
{
int value;
if(stackTop->next)
{
value = stackTop->next->info;
stackTop->next = stackTop->next->next;
}
else value = -1;
return value;
}