P3246 [HNOI2016] 序列 Solution
Description
给定序列 a = ( a 1 , a 2 , ⋯ , a n ) a=(a_1,a_2,\cdots,a_n) a=(a1,a2,⋯,an),处理 q q q 个查询 ( l , r ) (l,r) (l,r).
对每个查询求出 ∑ [ s , t ] ∈ [ l , r ] max i = s t a i \sum\limits_{[s,t]\in [l,r]}\max\limits_{i=s}^t a_i [s,t]∈[l,r]∑i=smaxtai.
Limitations
1 ≤ n , q ≤ 1 0 5 1\le n,q\le 10^5 1≤n,q≤105
∣ a i ∣ ≤ 1 0 9 |a_i|\le 10^9 ∣ai∣≤109
2 s , 500 MB 2\text{s},500\text{MB} 2s,500MB
Solution
扫描线做法.
将询问离线,挂在 r r r 上,从 1 ∼ n 1\sim n 1∼n 扫一遍,将子段转化为后缀.
我们用单调栈,在加入 a i a_i ai 前弹掉所有 > a i > a_i >ai 的数,并维护一个序列 w w w.
设弹出了 p p p,弹出后栈顶为 q q q,则需要在 w w w 上把 ( q , p ] (q,p] (q,p] 减去 a j a_j aj,加入 a i a_i ai 时将 ( top , i ] (\textit{top},i] (top,i] 加上 a i a_i ai.
维护完单调栈后,标记一个版本.
然后对每个 r = i r=i r=i 的查询,需要求 w l ⋯ r w_{l\cdots r} wl⋯r 的历史和.
直接上 loj193 维护 w w w 即可.
Code
3.12 KB , 0.96 s , 16.91 MB (in total, C++20 with O2) 3.12\text{KB},0.96\text{s},16.91\text{MB}\;\texttt{(in total, C++20 with O2)} 3.12KB,0.96s,16.91MB(in total, C++20 with O2)
线段树删了.
#include <bits/stdc++.h>
using namespace std;using i64 = long long;
using ui64 = unsigned long long;
using i128 = __int128;
using ui128 = unsigned __int128;
using f4 = float;
using f8 = double;
using f16 = long double;template<class T>
bool chmax(T &a, const T &b){if(a < b){ a = b; return true; }return false;
}template<class T>
bool chmin(T &a, const T &b){if(a > b){ a = b; return true; }return false;
}namespace seg_tree {}
using seg_tree::SegTree;
using pii = pair<int, int>;signed main() {ios::sync_with_stdio(0);cin.tie(0), cout.tie(0);int n, m;scanf("%d %d", &n, &m);vector<i64> a(n);for (int i = 0; i < n; i++) scanf("%lld", &a[i]);vector<vector<pii>> adj(n);for (int i = 0, l, r; i < m; i++) {scanf("%d %d", &l, &r), l--, r--;adj[r].emplace_back(l, i);}stack<int> stk;SegTree sgt(n);vector<i64> ans(m);for (int i = 0; i < n; i++) {while (!stk.empty() && a[stk.top()] > a[i]) {int j = stk.top(); stk.pop();if (stk.empty()) sgt.range_add(0, j, -a[j]);else sgt.range_add(stk.top() + 1, j, -a[j]);}if (stk.empty()) sgt.range_add(0, i, a[i]);else sgt.range_add(stk.top() + 1, i, a[i]);stk.push(i);sgt.apply(0, 0, 0, 1);for (auto [j, id] : adj[i]) ans[id] = sgt.range_hsum(j, i);}for (int i = 0; i < m; i++) printf("%lld\n", ans[i]);return 0;
}