跳到正文

题解

题解:P18114 [入门赛 #54] 找搭档

Wind__Chant约 4 分钟
原文
文章信息与版本

文章信息

发布
2026年11月27日
收录
2026年11月29日
更新
2026年11月29日
篇幅
约 4 分钟
获赞
1
题目
P18114

版本

  1. v1当前

题解:P18114 [入门赛 #54] 找搭档

思路

这道题目我一开始写了个暴力,只拿了 4848 分,所以肯定不能是暴力。

  • 然而,我们可以发现,只有相邻的两个人才有概率可以配对,所以我们每轮只处理当前队列中的相邻对就可以了。
  • 同时呢,我们还要用一个双向链表来维护更新队伍,lil_i、rir_i 表示左边和右边的邻居,这个时候如果要删除的话,复杂度就极低了。
  • 不难发现,同一轮的一个学生只能配对一次,所以我们还得用个数组标记一下,用来去重。
  • 删除之后,被删除的节点原来的左边和右边的邻居可能变成了新邻居,所以还需要把他们的关系也加入下一轮的队列。

代码

C++
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
const int N = 200005;
int h[N], L[N], R[N], ans[N];
bool vis[N], del[N];
int choose(int i) {
	int l = L[i], r = R[i];
	if (!l && !r) return 0;
	if (!l) return r;
	if (!r) return l;
	long long dl = (long long)h[i] - h[l];
	if (dl < 0) dl = -dl;
	long long dr = (long long)h[r] - h[i];
	if (dr < 0) dr = -dr;
	if (dl <= dr) return l;
	return r;
}
int main() {
	int n;
	cin >> n;
	for (int i = 1; i <= n; i++) cin >> h[i];
	for (int i = 1; i <= n; i++) {
		L[i] = i - 1;
		R[i] = (i == n) ? 0 : i + 1;
	}
	L[1] = 0;
	queue<pair<int, int>> q;
	for (int i = 1; i < n; i++) q.push({i, i + 1});
	int rnd = 0;
	while (!q.empty()) {
		rnd++;
		int sz = q.size();
		vector<pair<int, int>> nxt;
		vector<int> rm;
		for (int t = 0; t < sz; t++) {
			auto [i, j] = q.front();
			q.pop();
			if (R[i] != j || L[j] != i) continue;
			if (vis[i] || vis[j]) continue;
			if (choose(i) == j && choose(j) == i) {
				vis[i] = vis[j] = true;
				ans[i] = ans[j] = rnd;
				rm.push_back(i);
				rm.push_back(j);
			}
		}
		if (rm.empty()) break;
		for (int x : rm) del[x] = true;
		for (int x : rm) {
			int a = L[x], b = R[x];
			if (a) R[a] = b;
			if (b) L[b] = a;
		}
		for (int x : rm) {
			int a = L[x], b = R[x];
			if (a && !del[a]) {
				if (L[a]) nxt.push_back({L[a], a});
				if (R[a]) nxt.push_back({a, R[a]});
			}
			if (b && !del[b]) {
				if (L[b]) nxt.push_back({L[b], b});
				if (R[b]) nxt.push_back({b, R[b]});
			}
		}
		for (int x : rm) {
			del[x] = false;
			vis[x] = false;
		}
		for (auto &p : nxt) q.push(p);
	}
	for (int i = 1; i <= n; i++) {
		if (i > 1) cout << " ";
		cout << ans[i];
	}
}
原文
抓取于
  1. Wind__Chant

    qpqpqp