#include <iostream>
#include <vector>
#include <stack>
#include <tuple>
#include <algorithm>
using namespace std;
#define int long long
#define f first
#define s second
signed main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
int n, d; cin >> n >> d;
vector<int> c(n + 5, 0), pref(n + 5, 0);
for (int i = 1; i <= n; i++) {
cin >> c[i];
pref[i] = pref[i - 1] + c[i];
}
vector<vector<int>> par(n + 5, vector<int>(19, 0)), cost(n + 5, vector<int>(19, 0));
stack<pair<int, int>> stk;
stk.push(make_pair(-1, 0));
for (int i = 1; i <= n; i++) {
while (!stk.empty() && stk.top().f > c[i]) {
stk.pop();
}
par[i][0] = stk.top().s;
cost[i][0] = (i - stk.top().s) * c[i];
stk.push(make_pair(c[i], i));
}
for (int i = 1; i < 19; i++) {
for (int j = 1; j <= n; j++) {
par[j][i] = par[par[j][i - 1]][i - 1];
cost[j][i] = cost[par[j][i - 1]][i - 1] + cost[j][i - 1];
}
}
int q; cin >> q;
while (q--) {
int l, r; cin >> l >> r;
int ans = pref[r] - pref[l - 1], curr = c[r];
for (int i = 18; i >= 0; i--) {
if (par[r][i] >= l) {
ans -= cost[r][i];
r = par[r][i];
curr = c[r];
}
}
ans -= (r - l + 1) * curr;
cout << ans << "\n";
}
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |