题解:P17753 「RSOI-3B」序列 / sequence

· · 题解

提示:本文由 人类 生成,由 豆包 修改。

题意简述

给定长度为 n 的非负整数序列 a,选出整数 x\in[0,m],令 b_i=|a_i-x|,要求 b 单调不降。求满足条件的 x 的数量。

约束:1\le n\le 10^5,\;0\le a_i,m \le 10^9。

核心转化

条件 b_1\le b_2\le \dots \le b_n,等价于对每一组相邻元素:

|a_i - x| \le |a_{i+1}-x|

绝对值不等式性质:

|p-x|\le |q-x| \iff (p-x)^2 \le (q-x)^2

展开化简:

p^2-2px \le q^2-2qx 2(q-p)x \le q^2-p^2=(q-p)(q+p)

让我们分三种情况来讨论 p=a_i,q=a_{i+1}:

  1. x 是整数,上限取 $\boldsymbol{\left\lfloor \dfrac{p+q}{2} \right\rfloor = \dfrac{p+q}{2}}$(整数除法);
  2. x 是整数,下限取 $\boldsymbol{\left\lceil \dfrac{p+q}{2} \right\rceil=\dfrac{p+q+1}{2}}$。

也可以用几何理解:|p-x|=|q-x| 的分界点是 p,q 的中点。

算法流程

  1. 初始可行区间:L=0,\;R=m;
  2. 遍历每一对相邻 (a_i,a_{i+1}),算出约束:
    • 若 p<q:R \leftarrow \min(R,\lfloor \frac{p+q}{2}\rfloor)
    • 若 p>q:L \leftarrow \max(L,\lceil \frac{p+q}{2}\rceil)
  3. 所有约束取交之后:
    • 如果 L>R:没有合法 x,答案 0;
    • 否则答案为 R-L+1。

      代码

      
      #include <iostream>
      #include <vector>
      #include <algorithm>
      using namespace std;
      typedef long long ll;

int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n; ll m; cin >> n >> m; vector<ll> a(n); for (int i = 0; i < n; ++i) cin >> a[i]; ll L = 0, R = m; for (int i = 0; i + 1 < n; ++i) { ll p = a[i], q = a[i+1]; if (p == q) continue; ll s = p + q; if (p < q) { ll lim = s / 2; R = min(R, lim); } else { ll lim = (s + 1) / 2; L = max(L, lim); } } ll ans = 0; if (L <= R) ans = R - L + 1; cout << ans << '\n'; return 0; }


~~其实觉得更像黄题~~