刚开始把最大位置看成最大值, 我想这怎么写啊。。。
如果是最大位置的话, 我们能计算区间内每个值作为最大值的贡献,
然后拆成右边边第一个比它大的下标减去左边第一个比它大的下标, 然后离线之后就可以树状数组维护了。
#include<bits/stdc++.h> #define LL long long #define LD long double #define ull unsigned long long #define fi first #define se second #define mk make_pair #define PLL pair<LL, LL> #define PLI pair<LL, int> #define PII pair<int, int> #define SZ(x) ((int)x.size()) #define ALL(x) (x).begin(), (x).end() #define fio ios::sync_with_stdio(false); cin.tie(0); using namespace std; const int N = 1e6 + 7; const int inf = 0x3f3f3f3f; const LL INF = 0x3f3f3f3f3f3f3f3f; const int mod = 998244353; const double eps = 1e-8; const double PI = acos(-1); template<class T, class S> inline void add(T& a, S b) {a += b; if(a >= mod) a -= mod;} template<class T, class S> inline void sub(T& a, S b) {a -= b; if(a < 0) a += mod;} template<class T, class S> inline bool chkmax(T& a, S b) {return a < b ? a = b, true : false;} template<class T, class S> inline bool chkmin(T& a, S b) {return a > b ? a = b, true : false;} struct Bit { LL a[N]; void init() { memset(a, 0, sizeof(a)); } void modify(int x, int v) { if(!x) return; for(int i = x; i < N; i += i & -i) a[i] += v; } LL sum(int x) { LL ans = 0; for(int i = x; i; i -= i & -i) ans += a[i]; return ans; } LL query(int L, int R) { return sum(R) - sum(L - 1); } } bit[2]; int n, q, ql[N], qr[N]; int a[N], L[N], R[N]; int id[N]; LL ans[N]; stack<int> stk; vector<int> qus[N]; bool cmpr(const int& a, const int& b) { return qr[a] < qr[b]; } bool cmpl(const int& a, const int& b) { return ql[a] < ql[b]; } int main() { scanf("%d%d", &n, &q); for(int i = 1; i <= n; i++) scanf("%d", &a[i]); while(SZ(stk)) stk.pop(); for(int i = 1; i <= n; i++) { while(SZ(stk) && a[stk.top()] < a[i]) stk.pop(); L[i] = SZ(stk) ? stk.top() : 0; stk.push(i); } while(SZ(stk)) stk.pop(); for(int i = n; i >= 1; i--) { while(SZ(stk) && a[stk.top()] < a[i]) stk.pop(); R[i] = SZ(stk) ? stk.top() : n + 1; stk.push(i); } for(int i = 1; i <= q; i++) scanf("%d", &ql[i]), id[i] = i; for(int i = 1; i <= q; i++) scanf("%d", &qr[i]); sort(id + 1, id + 1 + q, cmpr); for(int i = 1, j = 1; i <= q; i++) { int x = id[i]; while(j <= qr[x]) bit[0].modify(L[j], L[j]), bit[1].modify(L[j], 1), j++; LL val = bit[0].query(ql[x], qr[x]), cnt = bit[1].query(ql[x], qr[x]); ans[x] -= val + 1LL * (qr[x] - ql[x] + 1 - cnt) * (ql[x] - 1); } sort(id + 1, id + 1 + q, cmpl); bit[0].init(); bit[1].init(); for(int i = q, j = n; i >= 1; i--) { int x = id[i]; while(j >= ql[x]) bit[0].modify(R[j], R[j]), bit[1].modify(R[j], 1), j--; LL val = bit[0].query(ql[x], qr[x]), cnt = bit[1].query(ql[x], qr[x]); ans[x] += val + 1LL * (qr[x] - ql[x] + 1 - cnt) * (qr[x] + 1); } for(int i = 1; i <= q; i++) printf("%lld%c", ans[i] - (qr[i] - ql[i] + 1), " "[i == q]); return 0; } /* */