-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstrong.c
More file actions
148 lines (95 loc) · 2.2 KB
/
strong.c
File metadata and controls
148 lines (95 loc) · 2.2 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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
/*
* @ Description -> Algorithm fo finding the strongly connected components of a graph.
* @ O(N^3) Complexity Time.
* @ License MIT
*/
#include <stdio.h>
#include <stdbool.h>
#define FIN "ctc.in"
#define FOUT "ctc.out"
#define MAX 10005
int mat[MAX][MAX];//matrix of adjacency
int SUCC[MAX], //array of succ
PREC[MAX]; //array of prec
int num_nodes, num_edges;
int num_components;
void DFS1(int node) {
int i;
SUCC[node] = num_components;
for(i = 1; i <= num_nodes; i++) {
if(mat[node][i] && !SUCC[ i ]) {
SUCC[i] = 1;
DFS1(i);
}
}
};
void DFS2(int node) {
int i;
PREC[node] = num_components;
for(i = 1; i <= num_nodes; i++) {
if(mat[i][node] && !PREC[ i ]) {
PREC[i] = 1;
DFS2(i);
}
}
};
void RoyWarshall() {
int i,j,k;
for(i=1;i<=num_nodes;i++) {
for(j=1;j<=num_nodes;j++) {
for(k=1;k<=num_nodes;k++) {
if(mat[i][k] && mat[k][j]) mat[i][j] = 1;
}
}
}
};
void read() {
int i,j;
freopen(FIN, "r", stdin);
scanf("%d %d", &num_nodes, &num_edges);
while(num_edges--)
{
scanf("%d %d", &i, &j);
mat[ i ][ j ] = 1;
};
RoyWarshall();
fclose( stdin );
};
int main() {
read();
int i,j;
for(i=1;i<=num_nodes;i++)
{
SUCC[i] = PREC[i] = 0;
}
num_components = 1;
for(i = 1; i <= num_nodes; i++)
{
if( !SUCC[ i ] )
{
DFS1( i );
DFS2( i );
for( j = 1; j <= num_nodes; j++)
{
if( SUCC[ j ] != PREC[ j ] ) SUCC[ j ] = PREC[ j ] = 0;
}
num_components++;
}
}
freopen(FOUT, "w", stdout);
printf("%d\n",num_components-1);
int num_comp = 1;
for( j = 1; j <= num_components; j++, num_comp)
{
for(i = 1; i <= num_nodes; i++)
{
if(SUCC[i] == j)
{
printf("%d ", i);
}
}
printf("\n");
}
fclose( stdout );
return(0);
};