跳到正文

个人记录

P10466 邻值查找

Adorkabless约 3 分钟
原文
文章信息与版本

文章信息

收录
2026年1月26日
更新
2026年1月31日
篇幅
约 3 分钟

版本

  1. v1当前
C++
#include<bits/stdc++.h>
//#define int long long
using namespace std;
struct Node {
	int x;
	int id;
} a[100005], ans[100005];
bool cmp(Node A, Node B) {
	if (A.x == B.x) return A.id < B.id;
	return A.x < B.x;
}
int ha[100005], nt[100005], l, r, p[100005];
signed main() {
	//freopen(".in", "r", stdin);
	//freopen(".out", "w", stdout);
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	int n;
	cin >> n;
	for (int i = 1; i <= n; i++) {
		cin >> a[i].x;//数值
		a[i].id = i;//原下标
	}
	sort(a + 1, a + 1 + n, cmp);
	l = 1, r = n;
	for (int i = 2; i <= n; i++) {
		ha[i] = i - 1;
	}
	for (int i = 1; i < n; i++) {
		nt[i] = i + 1;
	}
	for (int i = 1; i <= n; i++) {
		p[a[i].id] = i;//p[i] 原下标i现在在哪里
	}
	for (int i = n; i >= 2; i--) {
		if (p[i] == l) {//现在是第一个,计算和后一个的差
			ans[i].x = a[nt[p[i]]].x - a[p[i]].x;
			ans[i].id = a[nt[p[i]]].id;
			l = nt[l];//www 不能直接++
		} else if (p[i] == r) { //现在是最后一个计算和前一个的差
			ans[i].x = a[p[i]].x - a[ha[p[i]]].x;
			ans[i].id = a[ha[p[i]]].id;
			r = ha[r];//www 不能直接--
		} else {
			if ((a[p[i]].x - a[ha[p[i]]].x) <= (a[nt[p[i]]].x - a[p[i]].x)) {//注意符号
				ans[i].x = a[p[i]].x - a[ha[p[i]]].x;
				ans[i].id = a[ha[p[i]]].id;
			} else {
				ans[i].x = a[nt[p[i]]].x - a[p[i]].x;
				ans[i].id = a[nt[p[i]]].id;
			}
			nt[ha[p[i]]] = nt[p[i]];//弹出记得理清楚
			ha[nt[p[i]]] = ha[p[i]];
		}
	}
	for (int i = 2; i <= n; i++) cout << ans[i].x << " " << ans[i].id << endl;
	return 0;
}
原文