题解:P18114 [入门赛 #54] 找搭档
欢迎报名洛谷网校,报名课程可以获得对应组别的知识点讲解与答疑服务,期待和大家一起进步!点击图片即可报名。
:::align{center} :::
思路
每轮遍历整条队伍,最坏要花
假设两名学生在下一轮互选,而且他们各自的左右邻居与这一轮完全相同。两人的选择就都没有变,因此这一轮他们已经互选,轮末就该一起离开。这与他们还能在下一轮出现矛盾。所以,下一轮的每对搭档中,至少有一人的邻居在本轮删除后发生了变化。第一轮检查所有人,以后只检查邻居发生变化的人。检查学生
用数组模拟双向链表,
名单确定后,依次把其中的学生从链表摘掉。每次都用被摘学生此刻的左右邻居重新接起链表。比如样例 1 中,学生
q 保存当前轮的待检查学生。遍历完 q 并确定删除名单后,先清空 q,再一边摘除学生,一边把下一轮需要检查的人加入 q。若本轮找不到搭档,活动结束。答案数组初始为
第一轮有 vector 末尾追加的均摊时间为
#include <cstdlib>
#include <iostream>
#include <vector>
using namespace std;
const int N = 200000 + 5;
int h[N], pre[N], nxt[N], ans[N];
int del[N];
vector<int> q;
// 根据当前链表返回 x 选中的邻居,0 表示没有邻居。
int choose(int x) {
int l = pre[x], r = nxt[x];
if (l == 0) return r;
if (r == 0) return l;
if (abs(h[x] - h[l]) <= abs(h[x] - h[r])) return l;
return r;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
for (int i = 1; i <= n; ++i) {
cin >> h[i];
pre[i] = i - 1;
nxt[i] = (i < n ? i + 1 : 0);
q.push_back(i);
}
for (int round = 1; !q.empty(); ++round) {
int cnt = 0;
// 先确定本轮的全部搭档,再修改链表。
for (int i = 0; i < q.size(); i++) {
int x = q[i];
if (ans[x] != 0) continue;
int y = choose(x);
if (y == 0 || ans[y] != 0 || choose(y) != x) continue;
ans[x] = ans[y] = round;
del[++cnt] = x;
del[++cnt] = y;
}
if (cnt == 0) break;
q.clear();
for (int i = 1; i <= cnt; ++i) {
int x = del[i];
int l = pre[x], r = nxt[x];
if (l != 0) {
nxt[l] = r;
if (ans[l] == 0) q.push_back(l);
}
if (r != 0) {
pre[r] = l;
if (ans[r] == 0) q.push_back(r);
}
}
}
for (int i = 1; i <= n; ++i) {
cout << ans[i] << (i == n ? '\n' : ' ');
}
return 0;
}