跳到正文

题解

[P17090] 掐头去尾 题解

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

文章信息

发布
2026年7月11日
收录
2026年7月11日
更新
2026年11月16日
篇幅
约 4 分钟
题目
P17090

版本

  1. v2当前
  2. v1

我们追踪队首是什么。容易发现并归纳证明,队首维护的是前缀严格最大值,下简称前缀 max⁡\max。

将查询的序列中的前缀 max⁡\max 去除,剩下一个序列 a′a',当加入 a′a' 中的元素 ai′a_i' 时,队尾一定会变为 ai′a_i',根据前一个队尾即 ai−1′a_{i - 1}' 与 ai′a_i' 的大小关系,若 ai−1′≥ai′a_{i - 1}' \ge a_i',则队列长度加一。

于是答案即为 1+∑[ai−1′≥ai′]1 + \sum[a_{i - 1}' \ge a_i']。我们认为 a0′a'_0 是 ala_l,即加入的第一个元素。

这个做法目前和暴力模拟复杂度相同,考虑优化。

首先需要维护前缀 max⁡\max,这实际上就是单调栈。倒着扫一遍 aia_i,单调栈里面维护一个严格上升序列即可。

然后需要维护 ∑[ai−1′≥ai′]\sum[a_{i - 1}' \ge a_i']。若 axa_x 对应 ai′a_i',我们在 xx 这一处令 vx=[ai−1′≥ai′]v_x = [a_{i - 1}' \ge a_i'],那么查询 [l,r][l, r] 就相当于扫到 ll 时,查询 ∑i=lrvi\sum_{i = l} ^ r v_i。尝试维护 vv 的变化,当单调栈弹出一个下标 yy 时,此时 yy 前面的数都不是前缀 max⁡\max,vyv_y 变为 [ay≤ay−1][a_y\le a_{y - 1}];同时 yy 右边第一个非前缀 max⁡\max 的数 nxty\text{nxt}_y,其 vv 值变为 [anxty≤ay][a_{\text{nxt}_y}\le a_y]。

nxti\text{nxt}_i 可以在单调栈插入新值时维护,vv 可以用树状数组做单点加区间查。viv_i 值变化可以视作减去 viv_i 再加上变化成的新值,一个常数更小的方法是,维护 toi\text{to}_i 表示 vi=[ai≤atoi]v_i=[a_i\le a_{\text{to}_i}],然后每次修改就减掉 [ai≤atoi][a_i\le a_{\text{to}_i}],然后更新 toi\text{to}_i。

时间复杂度 O((n+q)log⁡n)\Omicron((n + q)\log n)。

code
C++
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 500007, p = 998244353;
int n, q, a[maxn], nxt[maxn], to[maxn], ans[maxn];
struct Qry {
	int r, id;
};
vector<Qry> Q[maxn];
struct BIT {
	int val[maxn];
	void add(int x, int k) {
		for (; x <= n; x += x & (-x)) val[x] += k;
	}
	int ask(int x) {
		int E = 0;
		for (; x; x -= x & (-x)) E += val[x];
		return E;
	}
}tr;
int main(void) {
	//freopen("data.in", "r", stdin);
	//freopen("data.out", "w", stdout);
	ios::sync_with_stdio(0), cin.tie(0);
	
	cin >> n >> q;
	for (int i = 1; i <= n; i++) cin >> a[i];
	for (int i = 1, l, r; i <= q; i++) {
		cin >> l >> r;
		Q[l].emplace_back(Qry{r, i});
	}
	vector<int> st;
	for (int i = n; i >= 1; i--) {
		for (; !st.empty() && a[st.back()] <= a[i]; ) {
			int v = st.back();
			tr.add(nxt[v], (a[nxt[v]] <= a[v]) - (a[nxt[v]] <= a[to[nxt[v]]]));
			to[nxt[v]] = v;
			tr.add(v, a[v] <= a[v - 1]), to[v] = v - 1;
			st.pop_back();
		}
		nxt[i] = i + 1;
		if (!st.empty() && st.back() == i + 1) nxt[i] = nxt[i + 1];
		st.emplace_back(i);
		for (auto x : Q[i]) {
			ans[x.id] = tr.ask(x.r) + 1;
		}
	}
	for (int i = 1; i <= q; i++) {
		cout << ans[i] << "\n";
	}
	
	return 0;
}
原文
存档评论1 条抓取于