boolean topological_sort( ) {
boolean Cycle;
for ( int i = 1 ; i <= N; i ++ ) {
Cycle = dfs( i) ;
if ( Cycle) return false ;
}
for ( int i = 1 ; i <= n; i ++ ) {
Numbers[ Stack.pop ( ) ] = i;
}
return true ;
}
boolean dfs( int v) {
if ( Color[ v] == 1 ) return true ;
if ( Color[ v] == 2 ) return false ;
Color[ v] = 1 ;
for ( int i = 0 ; i < Edges[ v] .size ( ) ; i ++ ) {
if ( dfs( Edges[ v] .get ( i) ) ) return true ;
}
Stack.push ( v) ;
Color[ v] = 2 ;
return false ;
}
Ym9vbGVhbiB0b3BvbG9naWNhbF9zb3J0KCl7CiAgICAgICBib29sZWFuIEN5Y2xlOwogICAgICAgZm9yKGludCBpID0gMTtpIDw9IE47aSArKyl7CiAgICAgICAgICAgQ3ljbGUgPSBkZnMoaSk7CiAgICAgICAgICAgaWYoQ3ljbGUpcmV0dXJuIGZhbHNlOwogICAgICAgfQogICAgICAgZm9yKGludCBpID0gMTtpIDw9IG47aSArKyl7CiAgICAgICAgICAgTnVtYmVyc1tTdGFjay5wb3AoKV0gPSBpOwogICAgICAgfQogICAgICByZXR1cm4gdHJ1ZTsKICB9CiAgYm9vbGVhbiBkZnMoaW50IHYpewogICAgICBpZihDb2xvclt2XSA9PSAxKXJldHVybiB0cnVlOwogICAgICBpZihDb2xvclt2XSA9PSAyKXJldHVybiBmYWxzZTsKICAgICAgQ29sb3Jbdl0gPSAxOwogICAgICBmb3IoaW50IGkgPSAwO2kgPCBFZGdlc1t2XS5zaXplKCk7aSArKyl7CiAgICAgICAgICBpZihkZnMoRWRnZXNbdl0uZ2V0KGkpKSlyZXR1cm4gdHJ1ZTsKICAgICAgfQogICAgICBTdGFjay5wdXNoKHYpOwogICAgICBDb2xvclt2XSA9IDI7CiAgICAgIHJldHVybiBmYWxzZTsKfQ==