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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int lcm ( int a , int b ) { return ( a * b ) / ( __gcd ( a , b ) ) ; } int dfs ( int src , vector < int > adj [ ] , vector < bool > & visited ) { visited [ src ] = true ; int count = 1 ; for ( int i = 0 ; i < adj [ src ] . size ( ) ; i ++ ) if ( ! visited [ adj [ src ] [ i ] ] ) count += dfs ( adj [ src ] [ i ] , adj , visited ) ; return count ; } int findMinTime ( int arr [ ] , int P [ ] , int n ) { vector < int > adj [ n + 1 ] ; for ( int i = 0 ; i < n ; i ++ ) { adj [ arr [ i ] ] . push_back ( P [ i ] ) ; } vector < bool > visited ( n + 1 ) ; int ans = 1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( ! visited [ i ] ) { ans = lcm ( ans , dfs ( i , adj , visited ) ) ; } } return ans ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 } ; int P [ ] = { 3 , 2 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findMinTime ( arr , P , n ) ; return 0 ; }