- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Minimum Number of Platforms Required for a Railway Station using C++.
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 −
Train | Arrival time | Departure time |
---|---|---|
Train-1 | 09:00 | 09:15 |
Train-2 | 09:35 | 11:45 |
Train-3 | 09:40 | 11:05 |
Train-4 | 11:00 | 12:00 |
Train-5 | 14:30 | 18:15 |
Train-6 | 18:00 | 19: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
Advertisements