int top = 0; for (int i = 1; i <= n; ++i) { while (top && a[stk[top]] < a[i]) rb[stk[top--]] = i; lb[i] = stk[top]; stk[++top] = i; } while (top) rb[stk[top--]] = n + 1;
int n, m; int a[N], lb[N], rb[N], stk[N]; LL ans[N]; Ask q[N]; vector<int> qry[N], del[N]; // qry[i]:左端点为i的询问,del[i]:lb为i的位置
structBit { LL tr[N]; inlinevoidclear(){ memset(tr, 0, sizeof tr); } inlinevoidupdate(int x, LL k){ for (int i = x; i <= n; i += i & -i) tr[i] += k; } inline LL query(int x){ LL re = 0; for (int i = x; i; i -= i & -i) re += tr[i]; return re; } } tr1, tr2;
intmain(){ read(n), read(m); for (int i = 1; i <= n; ++i) read(a[i]); for (int i = 1; i <= m; ++i) read(q[i].l); for (int i = 1; i <= m; ++i) read(q[i].r); // 单调栈求lb[i],rb[i] int top = 0; for (int i = 1; i <= n; ++i) { while (top && a[stk[top]] < a[i]) rb[stk[top--]] = i; if (top) lb[i] = stk[top]; stk[++top] = i; } while (top) rb[stk[top--]] = n + 1;
for (int i = 1; i <= n; ++i) del[lb[i]].push_back(i); for (int i = 1; i <= m; ++i) qry[q[i].l].push_back(i); for (int i = 1; i <= n; ++i) tr1.update(i, lb[i]); // 注意+1-1的细节 for (int i = 1; i <= n; ++i) { // 清除贡献,打tag for (int j = 0; j < del[i-1].size(); ++j) { tr1.update(del[i-1][j], -lb[del[i-1][j]]); tr2.update(del[i-1][j], 1); } for (int j = 0; j < qry[i].size(); ++j) { int id = qry[i][j]; ans[id] -= tr1.query(q[id].r) - tr1.query(q[id].l-1); ans[id] -= (LL)(i - 1) * (tr2.query(q[id].r) - tr2.query(q[id].l-1)); } } for (int i = 0; i <= n; ++i) del[i].clear(), qry[i].clear(); for (int i = 1; i <= n; ++i) del[rb[i]].push_back(i); for (int i = 1; i <= m; ++i) qry[q[i].r].push_back(i); tr1.clear(), tr2.clear(); for (int i = 1; i <= n; ++i) tr1.update(i, rb[i]-1); for (int i = n; i; --i) { for (int j = 0; j < del[i+1].size(); ++j) { tr1.update(del[i+1][j], -rb[del[i+1][j]]+1); tr2.update(del[i+1][j], 1); } for (int j = 0; j < qry[i].size(); ++j) { int id = qry[i][j]; ans[id] += tr1.query(q[id].r) - tr1.query(q[id].l-1); ans[id] += (LL)i * (tr2.query(q[id].r) - tr2.query(q[id].l-1)); } }
for (int i = 1; i <= m; ++i) printf("%lld ", ans[i]); puts(""); return0; }