餐厅最少桌子安排问题的 C++ 实现
以下是解决该问题的 C++ 代码: ```cpp #include <iostream> #include <vector> #include <queue> #include <algorithm> using namespace std; // 定义顾客结构体 struct Customer { int arrive_time; // 到达时间 int wait_time; // 最多等待时间 }; // 比较函数,用于优先队列,按离开时间排序 struct Compare { bool operator()(const int& a, const int& b) { return a > b; } }; int main() { int n, m; cin >> n >> m; // 输入顾客数量和用餐时间 vector<Customer> customers(n); for (int i = 0; i < n; ++i) { cin >> customers[i].arrive_time >> customers[i].wait_time; // 输入每位顾客的到达时间和最多等待时间 } priority_queue<int, vector<int>, Compare> tables; // 优先队列,存储每张桌子的空闲时间 int max_tables = 0; // 记录最多需要的桌子数 for (int i = 0; i < n; ++i) { // 检查当前空闲的桌子 while (!tables.empty() && tables.top() <= customers[i].arrive_time) { tables.pop(); } // 计算当前顾客离开的最晚时间 int leave_time = customers[i].arrive_time + customers[i].wait_time + m; // 如果没有空闲桌子,需要增加一张桌子 if (tables.size() == 0 || tables.top() > customers[i].arrive_time + customers[i].wait_time) { tables.push(leave_time); } else { // 有空闲桌子,更新该桌子的空闲时间 tables.pop(); tables.push(leave_time); } // 更新最多需要的桌子数 max_tables = max(max_tables, static_cast<int>(tables.size())); } cout << max_tables << endl; // 输出最少需要的桌子数 return 0; } ``` ### 代码解释: 1. **结构体 `Customer`**:用于存储每位顾客的到达时间和最多等待时间。 2. **优先队列 `tables`**:用于存储每张桌子的空闲时间,按空闲时间从小到大排序。 3. **遍历顾客**: - 对于每位顾客,检查当前空闲的桌子,如果有桌子在顾客到达时已经空闲,则将其从队列中移除。 - 计算当前顾客离开的最晚时间。 - 如果没有空闲桌子,需要增加一张桌子;否则,更新该桌子的空闲时间。 4. **更新最多需要的桌子数**:在遍历过程中,记录最多需要的桌子数。 5. **输出结果**:输出最少需要的桌子数。 ### 复杂度分析: - **时间复杂度**:$O(n log n)$,其中 $n$ 是顾客的数量。主要是优先队列的插入和删除操作的时间复杂度。 - **空间复杂度**:$O(n)$,主要是优先队列的空间开销。 ######[AI问答 | 729点数解答 | 2026-05-05 10:13:47]
- Python 实现球类:精准计算半径、表面积与体积,附输入验证与异常处理!(阿里通义 | 261点数解答 | 2024-11-28 21:19:39)401
- 51 单片机:定时器 0 实现 8 个 LED 循环点亮,附代码及优化建议(字节豆包 | 1193点数解答 | 2024-12-27 15:10:29)368
- 浙闽“板凳龙”舞龙队 300 秒螺线盘入:位置与速度全揭秘(阿里通义 | 886点数解答 | 2024-09-07 10:31:31)666
- 浙闽“板凳龙”舞龙队 300 秒位置与速度数学模型揭秘(GPT | 565点数解答 | 2024-09-07 10:32:56)558
- 223节板凳龙沿等距螺线盘入:300秒内位置与速度的数学揭秘 (讯飞星火 | 443点数解答 | 2024-09-07 10:34:10)409
- 浙闽“板凳龙”300秒舞龙轨迹与速度:数学模型揭秘!(字节豆包 | 522点数解答 | 2024-09-07 10:35:06)377
- Excel 销售数据难题:2024 年 Q3 及特定时段销售情况计算全攻略(字节豆包 | 762点数解答 | 2024-11-06 19:11:51)216
- 从封闭到觉醒:中国在西方文化冲击下的曲折蜕变(讯飞星火 | 331点数解答 | 2024-11-30 21:50:57)222
- 陈独秀〈吾人最后之觉悟〉:文化冲突下的觉醒与奋进之路(百度文心 | 458点数解答 | 2024-11-30 21:51:52)227
- 从文化冲突到国民觉悟:中国近代变革的觉醒之路( | 21点数解答 | 2024-11-30 21:52:33)220
- Python:生成含随机缺失值二维数组并处理,附随机选元素赋缺失值代码解析(阿里通义 | 300点数解答 | 2025-03-13 20:19:30)238
- 破解“没有3的世界”:找出第n个合规正整数!(DeepSeek | 471点数解答 | 2025-03-17 14:32:58)273