Railway Station | TCS CodeVita 2020 - GeeksforGeeks

07 Apr, 2022
Given an integer N, representing the number of stations lying between the source and the destination. There are three trains available from every station and their stoppage patterns are as follows:
Train 1: Stops at every station
Train 2: Stops at every alternate station
Train 3: Stops at every third station
The task is to find the number of ways to reach the destination from the source using any possible combination of trains.
Examples:
Input: N = 2 Output: 4Explanation: Four possible ways exists to travel from source to destination with 2 stations in between:Train 1 (from source) -> Train 1 (from station 1) -> Train 1(from station 2) -> DestinationTrain 2 (from source) -> Train 1 (from station 2) -> DestinationTrain 1 (from source) -> Train 2 (from station 1) -> DestinationTrain 3 (from source) -> Destination
Input: N = 0Output: 1Explanation: No station is present in between the source and destination. Therefore, there is only one way to travel, i.e.Train 1(from source) -> Destination
Approach: The main idea to solve the problem is to use Recursion with Memoization to solve this problem. The recurrence relation is as follows:
 F(N) = F(N – 1) + F(N – 2) + F(N – 3),
where,F(N – 1) counts ways to travel upto (N – 1)th station.F(N – 2) counts ways to travel upto (N – 2)th station.F(N – 3) counts ways to travel upto (N – 3)th station.
Follow the steps below to solve the problem:
Initialize an array dp[] for memorization. Set all indices to -1 initially.Define a recursive function findWays() to calculate the number of ways to reach the Nth station.Following base cases are required to be considered:For x < 0 return 0.For x = 0, return 1.For x = 1, return 2.For x = 2, return 4.If the current state, say x, is already evaluated i.e. dp[x] is not equal to -1, simply return the evaluated value.Otherwise, calculate findWays(x – 1), findWays(x – 2) and findWays(x – 3) recursively and store their sum in dp[x].Return dp[x].
Initialize an array dp[] for memorization. Set all indices to -1 initially.
Define a recursive function findWays() to calculate the number of ways to reach the Nth station.
Following base cases are required to be considered:For x < 0 return 0.For x = 0, return 1.For x = 1, return 2.For x = 2, return 4.
For x < 0 return 0.
For x = 0, return 1.
For x = 1, return 2.
For x = 2, return 4.
If the current state, say x, is already evaluated i.e. dp[x] is not equal to -1, simply return the evaluated value.
Otherwise, calculate findWays(x – 1), findWays(x – 2) and findWays(x – 3) recursively and store their sum in dp[x].
Return dp[x].
Below is the implementation of the above approach:
C++14
Java
Python3
Javascript
// C++ program of the above approach#include <bits/stdc++.h>using namespace std; // Dp table for memoizationint dp[100000]; // Function to count the number// of ways to N-th stationint findWays(int x){    // Base Cases    if (x < 0)        return 0;     if (x == 0)        return 1;     if (x == 1)        return 2;     if (x == 2)        return 4;     // If current state is    // already evaluated    if (dp[x] != -1)        return dp[x];     // Recursive calls     // Count ways in which    // train 1 can be chosen    int count = findWays(x - 1);     // Count ways in which    // train 2 can be chosen    count += findWays(x - 2);     // Count ways in which    // train 3 can be chosen    count += findWays(x - 3);     // Store the current state    dp[x] = count;     // Return the number of ways    return dp[x];} // Driver Codeint main(){     // Given Input    int n = 4;     // Initialize DP table with -1    memset(dp, -1, sizeof(dp));     // Function call to count    // the number of ways to    // reach the n-th station    cout << findWays(n) << "\n";}
// Java program for the above approachimport java.util.*;class GFG{   // Dp table for memoization  static int dp[] = new int[100000];   // Function to count the number  // of ways to N-th station  static int findWays(int x)  {     // Base Cases    if (x < 0)      return 0;     if (x == 0)      return 1;     if (x == 1)      return 2;     if (x == 2)      return 4;     // If current state is    // already evaluated    if (dp[x] != -1)      return dp[x];     // Recursive calls     // Count ways in which    // train 1 can be chosen    int count = findWays(x - 1);     // Count ways in which    // train 2 can be chosen    count += findWays(x - 2);     // Count ways in which    // train 3 can be chosen    count += findWays(x - 3);     // Store the current state    dp[x] = count;     // Return the number of ways    return dp[x];  }   // Driven Code  public static void main(String[] args)  {     // Given Input    int n = 4;     // Initialize DP table with -1    Arrays.fill(dp, -1);     // Function call to count    // the number of ways to    // reach the n-th station    System.out.print(findWays(n));  }} // This code is contributed by splevel62.
# Python3 program of the above approach # Dp table for memoizationdp = [-1 for i in range(100000)] # Function to count the number# of ways to N-th stationdef findWays(x):         # Base Cases    if (x < 0):        return 0     if (x == 0):        return 1     if (x == 1):        return 2     if (x == 2):        return 4     # If current state is    # already evaluated    if (dp[x] != -1):        return dp[x]     # Recursive calls     # Count ways in which    # train 1 can be chosen    count = findWays(x - 1)     # Count ways in which    # train 2 can be chosen    count += findWays(x - 2)     # Count ways in which    # train 3 can be chosen    count += findWays(x - 3)     # Store the current state    dp[x] = count     # Return the number of ways    return dp[x] # Driver Codeif __name__ == '__main__':         # Given Input    n = 4         # Function call to count    # the number of ways to    # reach the n-th station    print(findWays(n)) # This code is contributed by SURENDRA_GANGWAR
<script> // JavaScript program of the above approach // Dp table for memoizationlet dp = new Array(100000).fill(-1) // Function to count the number// of ways to N-th stationfunction findWays(x){         // Base Cases    if (x < 0)        return 0     if (x == 0)        return 1     if (x == 1)        return 2     if (x == 2)        return 4     // If current state is    // already evaluated    if (dp[x] != -1)        return dp[x]     // Recursive calls     // Count ways in which    // train 1 can be chosen    let count = findWays(x - 1)     // Count ways in which    // train 2 can be chosen    count += findWays(x - 2)     // Count ways in which    // train 3 can be chosen    count += findWays(x - 3)     // Store the current state    dp[x] = count     // Return the number of ways    return dp[x]} // Driver Code     // Given Inputlet n = 4 // Function call to count// the number of ways to// reach the n-th stationdocument.write(findWays(n)) // This code is contributed by shinjanpatra </script>
13
 
Time Complexity: O(N)Auxiliary Space: O(N)
 
SURENDRA_GANGWAR
splevel62
shinjanpatra
Memoization
Technical Scripter 2020
Dynamic Programming
Mathematical
Technical Scripter
Dynamic Programming
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bellman–Ford Algorithm | DP-23
Floyd Warshall Algorithm | DP-16
Subset Sum Problem | DP-25
Matrix Chain Multiplication | DP-8
Coin Change | DP-7
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
Merge two sorted arrays