forked from deutranium/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkosarajus.c
142 lines (127 loc) · 2.69 KB
/
kosarajus.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <assert.h>
#define N 100
#define I __INT_MAX__
typedef long long int ll;
typedef struct Node
{
ll vertex;
struct Node *next;
} Node;
void display(Node *first);
void push(struct Node *first, ll a);
bool isEmpty(struct Node *first);
ll pop(struct Node *first);
void display(Node *first)
{
struct Node *temp;
temp = first->next;
while (temp)
{
printf("%lld ", temp->vertex);
temp = temp->next;
}
printf("\n");
}
void push(struct Node *first, ll a)
{
struct Node *temp = (struct Node *)malloc(sizeof(struct Node));
temp->vertex = a;
temp->next = first->next;
first->next = temp;
}
bool isEmpty(struct Node *first)
{
if (first->next)
return 0;
else
return 1;
}
ll pop(struct Node *first)
{
if (isEmpty(first))
printf("The stack is empty\n");
else
{
Node *p = first;
p = p->next;
first->next = p->next;
ll temp = p->vertex;
free(p);
return temp;
}
}
void dfsL(Node *list, ll x, ll visited[], Node *st)
{
if (visited[x] == 0)
{
visited[x] = 1;
Node *temp;
temp = (list + x)->next;
while (temp)
{
dfsL(list, temp->vertex, visited, st);
temp = temp->next;
}
push(st, x);
}
}
void dfsR(Node *list, ll x, ll visited[])
{
if (visited[x] == 0)
{
visited[x] = 1;
printf("%lld ", x);
Node *temp;
temp = (list + x)->next;
while (temp)
{
dfsR(list, temp->vertex, visited);
temp = temp->next;
}
}
}
ll main()
{
// for kosarajus
ll n = 0, X = 0;
scanf("%lld %lld", &n, &X);
Node *adjList = (Node *)malloc((n + 1) * sizeof(Node));
Node *adjListR = (Node *)malloc((n + 1) * sizeof(Node));
Node *stack = (Node *)malloc(sizeof(Node));
stack->next = NULL;
stack->vertex = 0;
for (ll i = 0; i <= n; i++)
{
(adjList + i)->next = NULL;
(adjList + i)->vertex = 0;
(adjListR + i)->next = NULL;
(adjListR + i)->vertex = 0;
}
ll temp1, temp2;
for (ll i = 1; i <= X; i++)
{
scanf("%lld %lld", &temp1, &temp2);
push(adjList + temp1, temp2);
push(adjListR + temp2, temp1);
}
ll visited[N] = {0};
for (ll i = 1; i <= n; i++)
{
if (visited[i] == 0)
dfsL(adjList, i, visited, stack);
}
ll visitedR[N] = {0};
while (!isEmpty(stack))
{
ll i = pop(stack);
if (visitedR[i] == 0)
{
dfsR(adjListR, i, visitedR);
printf("\n");
}
}
return 0;
}