Maximum trains for which stoppage can be provided in C++


In this problem, we are given a number N denoting the number of platforms a station has with two tracks each. And T trains will be passing the station whose arrival and departure time are given. Each train stops at a specific station. Our task is to create a program to find the Maximum trains for which stoppage can be provided in C++.

Let’s take an example to understand the problem,

Input

N = 3, T = 5
Trains = {{0915, 0930, 2}, {0930, 0945, 1}, {0930, 1200, 1}, {0910, 0925, 3}, {0940, 1015, 1}}

Output

4

Explanation

The train schedules are,
Train 1: Train will be stopped at platform 2 - 09:15-09:30
Train 2: Train will be stopped at platform 1 - 09:30-09:45
Train 3: Train will be not be stopped
Train 4: Train will be stopped at platform 3 - 09:10-09:25
Train 5: Train will be stopped at platform 1 - 09:40-10:15

Solution Approach

The solution to the problem needs a greedy approach to be applied as we need to find the maximum number of trains that can be stopped at the station.

We will use the activity selection approach to find the most optimum solution to the problem. So, for each platform, we will create a vector to store the train’s information. And then find the most optimum solution.

Example

Program to illustrate the working of our problem,

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int maxStop(int trains[][3], int N, int T) {
   vector<pair<int, int> > tStopping[N + 1];
   int trainsStopped = 0;
   for (int i = 0; i < T; i++)
      tStopping[trains[i][2]].push_back( make_pair(trains[i][1], trains[i][0]));
      for (int i = 0; i <= N; i++)
         sort(tStopping[i].begin(), tStopping[i].end());
            for (int i = 0; i <= N; i++) {
               if (tStopping[i].size() == 0)
                  continue;
                  int a = 0;
                  trainsStopped++;
                  for (int j = 1; j < tStopping[i].size(); j++) {
                     if (tStopping[i][j].second >= tStopping[i][a].first) {
                        a = j;
                        trainsStopped++;
                     }
                  }
            }
            return trainsStopped;
}
int main(){
   int N = 3;
   int T = 5;
   int trains[T][3] = {{915, 930, 2}, {930, 945, 3}, {930, 1200, 1}, {910, 925, 3}, {940, 1015, 1}};
   cout<<"The Maximum No. of Trains Stopped at the station is "<<maxStop(trains, N, T);
   return 0;
}

Output

The Maximum No. of Trains Stopped at the station is 4

Updated on: 15-Oct-2020

178 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements