#include <iostream>
#include <vector>
#include <stack>
#include <tuple>
#include <cstdlib>
#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> ogc(n + 5, 0);
for (int i = 1; i <= n; i++) {
cin >> ogc[i];
}
vector<int> c(n + 5, 0), pref(n + 5, 0);
int mn = 0;
for (int i = n - 1; i >= 1; i--) {
if (ogc[i] >= ogc[i + 1]) {
c[i] = c[i + 1] + (ogc[i] - ogc[i + 1] + d - 1) / d;
} else {
c[i] = c[i + 1] - (ogc[i + 1] - ogc[i]) / d;
}
mn = min(mn, c[i]);
}
for (int i = 1; i <= n; i++) {
c[i] += (mn < 0 ? -mn : 0);
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;
if (ogc[l] - (c[l] - curr) * d < 0) {
cout << -1 << "\n";
continue;
}
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... |