Minimum Number of Platforms Required for a Railway Station using C++.

C++Server Side ProgrammingProgramming

Problem statement

Given arrival and departure times of all trains that reach a railway station, the task is to find the minimum number of platforms required for the railway station so that no train waits.

We are given two arrays that represent arrival and departure times of trains that stop.

For below input, we need at least 3 platforms −

TrainArrival timeDeparture time
Train-109:0009:15
Train-209:3511:45
Train-309:4011:05
Train-411:0012:00
Train-514:3018:15
Train-618:0019:00

Algorithm

1. Sort arrival and departure time arrays in ascending order
2. Trace the number of trains at any time keeping track of trains that haves arrived, but not departed

Example

#include <iostream>
#include <algorithm>
#define SIZE(arr) (sizeof(arr) / sizeof(arr[0]))
using namespace std;
int getPlatformCount(int *arrival, int *departure, int n){
   sort(arrival, arrival + n);
   sort(departure, departure + n);
   int platformCnt = 1;
   int result = 1;
   int i = 1;
   int j = 0;
   while (i < n && j < n) {
      if (arrival[i] <= departure[j]) {
         ++platformCnt;
         ++i;
         if (platformCnt > result) {
            result = platformCnt;
         }
      } else {
         --platformCnt;
         ++j;
      }
   }
   return result;
}
int main()
{
   int arrival[] = {900, 935, 940, 1100, 1430, 1800};
   int departure[] = {915, 1145, 1105, 1200, 1815, 1900};
   cout << "Minimum required platforms = " <<
   getPlatformCount(arrival, departure, SIZE(arrival)) << endl;
   return 0;
}

Output

When you compile and execute the above program. It generates the following output −

Minimum required platforms = 3
raja
Published on 31-Oct-2019 07:34:28
Advertisements