text: Total time required to travel a path denoted by a given string | C ++ code for the above approach ; Function to calculate time taken to travel the path ; Stores total time ; Initial position ; Stores visited segments ; Check whether segment is present in the set ; Increment the value of time by 2 ; Insert segment into the set ; Print the value of time ; Driver Code
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; void calcTotalTime ( string path ) { int time = 0 ; int x = 0 , y = 0 ; set < pair < int , int > > s ; for ( int i = 0 ; i < path . size ( ) ; i ++ ) { int p = x ; int q = y ; if ( path [ i ] == ' N ' ) y ++ ; else if ( path [ i ] == ' S ' ) y -- ; else if ( path [ i ] == ' E ' ) x ++ ; else if ( path [ i ] == ' W ' ) x -- ; if ( s . find ( { p + x , q + y } ) == s . end ( ) ) { time += 2 ; s . insert ( { p + x , q + y } ) ; } else time += 1 ; } cout << time << endl ; } int main ( ) { string path = " NSE " ; calcTotalTime ( path ) ; return 0 ; }