#include <bits/stdc++.h>
using namespace std;
#define int long long
int n, d, q, a[300005], b[300005], c[300005], pre[300005], ans[300005];
pair<int, int> up[300005][19];
pair<pair<int, int>, int> qu[300005];
int32_t main() {
ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
cin >> n >> d;
for (int i = 1 ; i <= n; i++) {
cin >> a[i]; c[i] = a[i];
b[i] = a[i] / d;
c[i] %= d;
if (c[i] < c[i - 1]) {
int tmp = (c[i - 1] - c[i] + d - 1) / d;
b[i] -= tmp;
c[i] += tmp * d;
}
pre[i] = pre[i - 1] + b[i];
}
vector<int> st;
for (int i = n; i >= 1; i--) {
while (!st.empty() && a[st.back()] > a[i]) {
// l = i + 1, r = st.back()
int ex = c[i + 1] / d, res;
int tmp = c[st.back()] - ex * d;
ex -= (a[st.back()] - tmp) / d;
if (b[st.back()] < -ex) res = -4e18;
else res = pre[st.back() - 1] - pre[i] + ex * (st.back() - i - 1);
up[st.back()][0] = {i, res};
st.pop_back();
}
st.push_back(i);
}
for (int i = 1; i <= n; i++)
for (int j = 1; j <= 18; j++)
up[i][j] = {up[up[i][j - 1].first][j - 1].first,
max(up[i][j - 1].second + up[up[i][j - 1].first][j - 1].second, (int) -4e18)};
cin >> q;
for (int i = 0; i < q; i++) {
int l, r; cin >> l >> r; int ans = 0;
for (int i = 18; i >= 0; i--)
if (up[r][i].first >= l)
ans += up[r][i].second, r = up[r][i].first;
int ex = c[l] / d;
if (b[r] < -ex) { cout << -1 << '\n'; continue; }
int tmp = c[r] - ex * d;
ex -= (a[r] - tmp) / d;
ans += pre[r - 1] - pre[l - 1] + ex * (r - l);
cout << (ans < 0 ? -1 : 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... |