55
66/*
77 * Author : joney_000[developer.jaswant@gmail.com]
8- * Algorithm : N/A
8+ * Algorithm : DFS or similar
99 * Platform : Codeforces
10- * Ref :
10+ * Ref : Cycle detection in forest
1111 */
1212
1313class A {
@@ -56,11 +56,11 @@ void run()throws Exception{
5656 int u = i (); int v = i ();
5757 adj [u ].add (v ); // directed graph
5858 }
59-
59+ LinkedList < Integer >[] adj0 = getCopy ( adj , n ); // maintaining mutability
6060 boolean isCycle = false ;
6161 for (int i = 1 ; i <= n ; i ++){
62- if (!visited [i ]){
63- ans = ans | isCycle (i ); //PS: Not connected Graph: i.e. forest containing disconnected components
62+ if (!vis [i ]){
63+ isCycle = isCycle | isCycle (i , adj0 ); //PS: Not connected Graph: i.e. forest containing disconnected components
6464 if (isCycle ){
6565 break ;
6666 }
@@ -80,7 +80,21 @@ void clear(int n){
8080 }
8181 }
8282
83- boolean dfs (int root )throws Exception {
83+ // Maintain mutability
84+ LinkedList <Integer >[] getCopy (LinkedList <Integer >[] adj , int n )throws Exception {
85+ LinkedList <Integer > adj_copy [] = new LinkedList [n + 1 ];
86+ for (int i = 1 ; i <= n ; i ++){
87+ adj_copy [i ] = new LinkedList <Integer >();
88+ for (int x : adj [i ]){
89+ adj_copy [i ].add (x );
90+ }
91+ }
92+ return adj_copy ;
93+ }
94+
95+ // int []depth = new int[MAXN + 1];
96+
97+ boolean isCycle (int root , LinkedList <Integer >[] adj )throws Exception {
8498
8599 LinkedList <Integer > queue = new LinkedList <Integer >(); //the stack
86100 int depth = 0 ; // level
@@ -101,7 +115,7 @@ boolean dfs(int root)throws Exception{
101115 return true ;
102116 }
103117 }else {
104- int v = q .removeLast ();
118+ int v = queue .removeLast ();
105119 depth --;
106120 }
107121 }
@@ -471,4 +485,4 @@ public int compareTo(Pair p){
471485 public String toString (){
472486 return "a = " + this .a + " b = " + this .b ;
473487 }
474- }
488+ }
0 commit comments