-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkosaraju.list.cpp
More file actions
129 lines (84 loc) · 2.01 KB
/
kosaraju.list.cpp
File metadata and controls
129 lines (84 loc) · 2.01 KB
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
#include <stdio.h>
#define MAXN 100005
#define FIN "ctc.in"
#define FOUT "ctc.out"
struct Node {
int y;
Node *next;
} *L1[ MAXN ], //first list
*L2[ MAXN ], //second list
*Comp[ MAXN ];//this array of pointers holds the strongly connected connex.
int countComp = 0;
int post[ MAXN ];
int visited[ MAXN ];
int nodes,//number of nodes
edges;//number of edges
void DFS(int node) {
visited[ node ] = 1;
for(Node *q = L1[ node ]; q; q = q->next) {
if(!visited[ q->y ]) {
DFS( q->y );
}
}
post[ ++post[ 0 ] ] = node;
};
void DFSR(int node) {
visited[ node ] = 0;
Node *q = new Node;
q->y = node;
q->next = Comp[ countComp ];
Comp[ countComp ] = q;
for(Node *q = L2[ node ]; q; q = q->next) {
if(visited[ q->y ] == 1) {
DFSR( q->y );
}
}
};
void readData() {
Node *q1, *q2;
int x,
y;
FILE *in = fopen(FIN, "r");
fscanf(in, "%d %d", &nodes, &edges);
while(edges--) {
fscanf(in, "%d %d", &x, &y);
q1 = new Node;
q1->y = y;
q1->next = L1[ x ];
L1[ x ] = q1;
q2 = new Node;
q2->y = x;
q2->next = L2[ y ];
L2[ y ] = q2;
}
fclose( in );
}
void Kosaraju() {
for(int node = 1; node <= nodes; node++) {
if( !visited[ node ] ) {
DFS( node );
}
}
for(int i = nodes; i >= 1; --i) {
if(visited[ post[ i ] ] == 1) {
++countComp;
DFSR( post[ i ] );
}
}
}
void writeComponents() {
FILE *out = fopen(FOUT, "w");
fprintf(out, "%d\n", countComp);
for(int i = 1; i <= countComp; ++i, fprintf(out, "\n")) {
for(Node *R = Comp[ i ]; R; R = R->next) {
fprintf(out, "%d ", R->y);
}
}
fclose( stdout );
}
int main() {
readData();
Kosaraju();
writeComponents();
return(0);
};