题解:P13978 数列分块入门 3

· · 题解

Upd 2025.9.7: 调整题意及代码部分描述。

前日谈(发会牢骚)

悲报:

但是:

然后:

建议以后洛谷把审核题解的人以及审核的题解全部公开,方便我去和 Ta 们对线。

题意

给出一个长为 n 的数列,以及 n 个操作,操作有两种(\mathrm{opt}\in\{0,1\}),涉及:

  1. 区间加(\mathrm{opt}=0),令 \forall i \in [l,r],a_i \leftarrow a_i+c。
  2. 区间查询(\mathrm{opt}=1),询问在区间 [l,r] 中 c 的前驱(比其小的最大元素)的值。若无,输出 -1。
## 题解 此题其实和 [P13977 数列分块入门 2](https://www.luogu.com.cn/problem/P13977) 是本质相同的。前驱指的是“比这个数小的数中的最大值”,则我们就是在所有 $< c$ 的 $a_i$ 中找 $a_i$ 的最大值。把上一题的累加器改成存储最大值,这题就差不多了。 简单概括一下:对于修改,整块直接懒标记,反之暴力修改,并进行排序保证其所在整块的单调性;对于查询,整块用 `lower_bound` 找到第一个 $< c$ 的位置,它的前一个位置就是这个整块中 $c$ 的前驱,与答案求最大值,对于散块(散点),暴力去求即可。 ## 代码 仍然保留注释。虽然题目说保证在 $32$ 位整数内可存储,但我的代码不开 `long long` 就会 RE。这可能是个人实现问题,大家自己看着要不要加。 ```cpp // 和第二问差不多啦,就是query改了一点 #include <iostream> #include <cmath> #include <algorithm> #include <vector> #include <climits> using namespace std; typedef long long ll; const int N = 1e6+5; const ll mn = -9223372036854775807; int n, blo, bl[N]; ll v[N], atag[N]; vector <ll> vec[N]; // 十年OI void resort(int x){ vec[x].clear(); for (int i = (x-1)*blo+1; i <= min(x*blo, n); i++) vec[x].push_back(v[i]); sort(vec[x].begin(), vec[x].end()); } void add(int a, int b, int c){ for (int i = a; i <= min(bl[a]*blo, b); i++) v[i] += c; resort(bl[a]); if (bl[a] != bl[b]){ for (int i = (bl[b]-1)*blo+1; i <= b; i++) v[i] += c; resort(bl[b]); } for (int i = bl[a]+1; i <= bl[b]-1; i++) atag[i] += c; } int query(int a, int b, int c){ // 求<c的max ll res = mn; // 记得看值域 for (int i = a; i <= min(bl[a]*blo, b); i++) if (v[i]+atag[bl[a]] < c) res = max(res, v[i]+atag[bl[a]]); if (bl[a] != bl[b]) for (int i = (bl[b]-1)*blo+1; i <= b; i++) if (v[i]+atag[bl[b]] < c) res = max(res, v[i]+atag[bl[b]]); for (int i = bl[a]+1; i <= bl[b]-1; i++){ int x = lower_bound(vec[i].begin(), vec[i].end(), c-atag[i])-vec[i].begin(); // 由于atag标记未下传到v[i],给c-atag相当于v[i]+atag了 if (x == 0) continue; // 记住这里要判一下防止下面x-1越界 res = max(res, vec[i][x-1]+atag[i]); // 记得给atag加回去 } if (res == mn) return -1; return res; } int main(){ ios::sync_with_stdio(0); cin.tie(0); cin >> n; blo = sqrt(n); for (int i = 1; i <= n; i++){ cin >> v[i]; bl[i] = (i-1)/blo+1; vec[bl[i]].push_back(v[i]); } for (int i = 1; i <= bl[n]; i++) sort(vec[i].begin(), vec[i].end()); for (int i = 1, f, a, b, c; i <= n; i++){ cin >> f >> a >> b >> c; if (f == 0) add(a, b, c); else cout << query(a, b, c) << '\n'; } return 0; } ```