-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkosaraju.list2.cpp
More file actions
116 lines (73 loc) · 1.82 KB
/
kosaraju.list2.cpp
File metadata and controls
116 lines (73 loc) · 1.82 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
#include <cstdio>
#include <vector>
#define MAXN 100005
#define FIN "ctc.in"
#define FOUT "ctc.out"
using namespace std;
vector<int> L1[ MAXN ], //First list
L2[ MAXN ], //Second list
Comp[ MAXN ]; //components List
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(int i = 0; i < L1[ node ].size(); i++) {
if(!visited[ L1[node][i] ]) {
DFS( L1[node][i] );
}
}
post[ ++post[ 0 ] ] = node;
};
void DFSR(int node) {
visited[ node ] = 0;
Comp[ countComp ].push_back( node );
for(int i = 0 ; i < L2[ node ].size(); i++) {
if(visited[ L2[node][i] ] == 1) {
DFSR( L2[node][i] );
}
}
};
void readData() {
int x,
y;
FILE *in = fopen(FIN, "r");
fscanf(in, "%d %d", &nodes, &edges);
while(edges--) {
fscanf(in, "%d %d", &x, &y);
L1[ x ].push_back( y );
L2[ y ].push_back( x );
}
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(int j = 0; j < Comp[ i ].size(); j++ ) {
fprintf(out, "%d ", Comp[ i ][ j ]);
}
}
fclose( stdout );
}
int main() {
readData();
Kosaraju();
writeComponents();
return(0);
};