Minimum time to reach from Node 1 to N if travel is allowed only when node is Green | Import library for Queue ; Function to find min edge ; Initialize queue and push [ 1 , 0 ] ; Create visited array to keep the track if node is visited or not ; Run infinite loop ; If node is N , terminate loop ; Travel adjacent nodes of crnt ; Check whether we visited previously or not ; Push into queue and make as true ; Function to Find time required to reach 1 to N ; Check color of node is red or green ; Add C sec from next green color time ; Add C ; Return the answer ; Driver Code ; Given Input ; Function Call ; Print total time
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minEdge ( vector < vector < int > > X , int N , int M , int T , int C ) { queue < pair < int , int > > Q ; Q . push ( { 1 , 0 } ) ; vector < int > V ( N + 1 , false ) ; int crnt , c ; while ( 1 ) { crnt = Q . front ( ) . first ; c = Q . front ( ) . second ; Q . pop ( ) ; if ( crnt == N ) break ; for ( int _ : X [ crnt ] ) { if ( ! V [ _ ] ) { Q . push ( { _ , c + 1 } ) ; V [ _ ] = true ; } } } return c ; } int findTime ( int T , int C , int c ) { int ans = 0 ; for ( int _ = 0 ; _ < c ; _ ++ ) { if ( ( ans / T ) % 2 ) ans = ( ans / T + 1 ) * T + C ; else ans += C ; } return ans ; } int main ( ) { int N = 5 ; int M = 5 ; int T = 3 ; int C = 5 ; vector < vector < int > > X { { } , { 2 , 3 , 4 } , { 4 , 5 } , { 1 } , { 1 , 2 } , { 2 } } ; int c = minEdge ( X , N , M , T , C ) ; int ans = findTime ( T , C , c ) ; cout << ( ans ) << endl ; return 0 ; }