【STL set】就近落座(seat)
【STL set】就近落座(seat)
一、题意
一排有 个座位,编号 ,初始全部为空。依次到来 位来客,第 位希望坐在 号座位。
每人必须选择与 距离最近的空座位;如果距离相同,优先选择编号较小的座位。如果没有空座,输出 。
数据范围:,。
二、朴素算法
每次枚举所有 个座位,寻找距离 最近的空座位,若距离相同则取编号较小者。
单次 ,总时间复杂度 ,最坏约 次检查,会超时。
三、关键性质
设当前来客希望坐在 号座位。
如果左边存在空座,那么左边最接近 的空座一定比其他左边空座更优;右边同理。
因此答案只可能是不大于 的最大空座位与不小于 的最小空座位之一。相等时取左边(编号小)。
使用有序集合 set<int> 存储所有空座位:
lower_bound(x)找到第一个不小于 的空座位,即右侧候选。- 如果该迭代器不等于
begin(),它的前一个元素就是左侧候选。 - 比较左右距离,取更近者;距离相同取左边。
- 输出结果,并从集合中删除该座位。
注意:lower_bound(x) 可能等于 end(),不能直接解引用;begin() 也不能向前移动。
四、C++14 代码
#include <bits/stdc++.h>
using namespace std;
int main() {
freopen("seat.in", "r", stdin);
freopen("seat.out", "w", stdout);
int n, k;
cin >> n >> k;
set<int> s;
for (int i = 1; i <= k; i++) {
s.insert(i);
}
for (int i = 1; i <= n; i++) {
int x;
cin >> x;
if (s.empty()) {
cout << 0 << " ";
continue;
}
auto it = s.lower_bound(x);
int l = -1, r = -1;
if (it != s.end()) r = *it;
if (it != s.begin()) l = *prev(it);
int p;
if (l == -1) p = r;
else if (r == -1) p = l;
else if (x - l <= r - x) p = l;
else p = r;
cout << p << " ";
s.erase(p);
}
cout << "\n";
return 0;
}
提交说明: 若评测平台采用标准输入输出,而不是文件输入输出,删除两行 freopen 即可。
五、样例模拟
输入:
4 3
2 2 2 1
| 来客 | 希望座位 | 当前空座 | 实际座位 |
|---|---|---|---|
| 1 | 2 | 1, 2, 3 | 2 |
| 2 | 2 | 1, 3 | 1 |
| 3 | 2 | 3 | 3 |
| 4 | 1 | 无 | 0 |
输出:2 1 3 0。
六、复杂度分析
初始化集合需要 时间。每位来客的 lower_bound 和 erase 分别需要 时间,其余操作为 。
- 时间复杂度: 。
- 空间复杂度: 。
能够通过全部数据。