Minimum time to return array to its original state after given modifications | C # implementation of above approach ; Function to return lcm of two numbers ; Make a graph ; Add edge ; Count reachable nodes from every node . ; Driver code
using System ; using System . Collections . Generic ; class GFG { static int lcm ( int a , int b ) { return ( a * b ) / ( __gcd ( a , b ) ) ; } static int __gcd ( int a , int b ) { return b == 0 ? a : __gcd ( b , a % b ) ; } static int dfs ( int src , List < int > [ ] adj , bool [ ] visited ) { visited [ src ] = true ; int count = 1 ; for ( int i = 0 ; i < adj [ src ] . Count ; i ++ ) if ( ! visited [ adj [ src ] [ i ] ] ) count += dfs ( adj [ src ] [ i ] , adj , visited ) ; return count ; } static int findMinTime ( int [ ] arr , int [ ] P , int n ) { List < int > [ ] adj = new List < int > [ n + 1 ] ; for ( int i = 0 ; i < n + 1 ; i ++ ) adj [ i ] = new List < int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { adj [ arr [ i ] ] . Add ( P [ i ] ) ; } bool [ ] visited = new bool [ n + 1 ] ; int ans = 1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( ! visited [ i ] ) { ans = lcm ( ans , dfs ( i , adj , visited ) ) ; } } return ans ; } public static void Main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 3 } ; int [ ] P = { 3 , 2 , 1 } ; int n = arr . Length ; Console . Write ( findMinTime ( arr , P , n ) ) ; } }