给定到达火车站的所有火车的到达和离开时间,任务是找到火车站所需的最少平台数目,以便没有火车在等待。
我们得到了两个数组,分别表示停靠的火车的到达和离开时间。
对于以下输入,我们至少需要3个平台-
培养 | 到达时间 | 出发时间 |
---|---|---|
火车1 | 09:00 | 09:15 |
火车2 | 09:35 | 11:45 |
火车3 | 09:40 | 11:05 |
火车4 | 11:00 | 12:00 |
火车5 | 14:30 | 18:15 |
火车6 | 18:00 | 19:00 |
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
#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; }
输出结果
当您编译并执行上述程序时。它生成以下输出-
Minimum required platforms = 3