-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathBOTTOM.cpp
More file actions
88 lines (80 loc) · 1.98 KB
/
BOTTOM.cpp
File metadata and controls
88 lines (80 loc) · 1.98 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
#include <cstdio>
#include <vector>
#include <queue>
#define MAXN 5000
using namespace std;
vector< int > graph[ MAXN + 1 ], graphT[ MAXN + 1 ], sorted;
bool visited[ MAXN + 1 ];
int comp[ MAXN + 1 ], sol[ MAXN + 1 ];
int N, M;
void init( int N ) {
for ( int i = 0; i <= N; ++i ) {
graph[ i ].clear();
graphT[ i ].clear();
visited[ i ] = false;
}
sorted.clear();
}
void dfs1( int S ) {
visited[ S ] = true;
int i;
for ( i = 0; i < graph[ S ].size(); ++i ) {
if ( !visited[ graph[ S ][ i ] ] ) {
dfs1( graph[ S ][ i ] );
}
}
sorted.push_back( S );
}
void dfs2( int S, int c ) {
visited[ S ] = false;
comp[ S ] = c;
int i;
for ( i = 0; i < graphT[ S ].size(); ++i ) {
if ( visited[ graphT[ S ][ i ] ] ) {
dfs2( graphT[ S ][ i ], c );
}
}
}
int main() {
int i, j, u, v, compon;
while ( 1 ) {
scanf( "%d", &N );
if ( N == 0 ) {
break;
}
scanf( "%d", &M );
init( N );
for ( i = 0; i < M; ++i ) {
scanf( "%d%d", &u, &v );
graph[ u ].push_back( v );
graphT[ v ].push_back( u );
}
for ( i = 1; i <= N; ++i ) {
if ( !visited[ i ] ) {
dfs1( i );
}
}
compon = 0;
for ( i = sorted.size() - 1; i >= 0; --i ) {
if ( visited[ sorted[ i ] ] ) {
dfs2( sorted[ i ], compon++ );
sol[ compon - 1 ] = true;
}
}
for ( i = 1; i <= N; ++i ) {
for ( j = 0; j < graph[ i ].size(); ++j ) {
if ( comp[ i ] != comp[ graph[ i ][ j ] ] ) {
sol[ comp[ i ] ] = false;
break;
}
}
}
for ( i = 1; i <= N; ++i ) {
if ( sol[ comp[ i ] ] ) {
printf( "%d ", i );
}
}
printf( "\n" );
}
return 0;
}