22 " https://judge.yosupo.jp/problem/cycle_detection"
33#include " ../template.hpp"
44#include " ../scc_asserts.hpp"
5- #include " ../../../library/graphs/strongly_connected_components/add_edges_strongly_connected.hpp"
65int main () {
76 cin.tie (0 )->sync_with_stdio (0 );
87 int n, m;
@@ -17,43 +16,45 @@ int main() {
1716 }
1817 scc_asserts (adj);
1918 auto [num_sccs, scc_id] = sccs (adj);
20- vector< int > color (n);
21- vector<
22- pair< int /* edge id */ , int /* node closer to root */ >>
23- edge_stack;
24- auto dfs = [&]( auto && self, int u) -> void {
25- for ( auto [v, e_id] : adj_edge_id[u]) {
26- if (color[v] == 0 ) {
27- color[v] = 1 ;
28- edge_stack. emplace_back (e_id, u) ;
29- self (self, v);
30- edge_stack. pop_back ();
31- color[v] = 2 ;
32- } else if (color[v] == 1 ) {
33- vector< int > res ( 1 , e_id );
34- while (1 ) {
35- auto [curr_edge_id, curr_node ] =
36- edge_stack. back ();
37- edge_stack. pop_back ();
38- assert (scc_id[curr_node] == scc_id[u]) ;
39- res. push_back (curr_edge_id) ;
40- if (curr_node == v) break ;
19+ if (num_sccs == n) {
20+ cout << - 1 << ' \n ' ;
21+ return 0 ;
22+ }
23+ vi scc_siz (num_sccs);
24+ vi any_node (num_sccs);
25+ rep (i, 0 , n ) {
26+ any_node[scc_id[i]] = i ;
27+ scc_siz[scc_id[i]]++ ;
28+ }
29+ rep (i, 0 , num_sccs) {
30+ if (scc_siz[i] > 1 ) {
31+ int v = any_node[i];
32+ vi vis (n );
33+ while (!vis[v] ) {
34+ vis[v ] = 1 ;
35+ for ( auto [next, _] : adj_edge_id[v]) {
36+ if (scc_id[v] == scc_id[next]) {
37+ v = next ;
38+ break ;
39+ }
4140 }
42- cout << sz (res) << ' \n ' ;
43- for (int i = sz (res) - 1 ; i >= 0 ; i--)
44- cout << res[i] << ' \n ' ;
45- exit (0 );
4641 }
47- }
48- };
49- for (int i = 0 ; i < n; i++) {
50- if (color[i] == 0 ) {
51- color[i] = 1 ;
52- dfs (dfs, i);
53- color[i] = 2 ;
42+ vi cycle;
43+ while (vis[v] == 1 ) {
44+ vis[v] = 2 ;
45+ for (auto [next, e_id] : adj_edge_id[v]) {
46+ if (scc_id[v] == scc_id[next]) {
47+ cycle.push_back (e_id);
48+ v = next;
49+ break ;
50+ }
51+ }
52+ }
53+ cout << sz (cycle) << ' \n ' ;
54+ for (int node : cycle) cout << node << ' \n ' ;
55+ return 0 ;
5456 }
5557 }
56- assert (num_sccs == n);
57- cout << -1 << ' \n ' ;
58+ assert (0 );
5859 return 0 ;
5960}
0 commit comments