#include <bits/stdc++.h>
#define int long long
using namespace std;
int a[300005], b[300005], c[300005], ind[300005][20], cost[300005][20];
stack<int> s;
signed main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n, d, q;
cin >> n >> d;
for (int i=1; i<=n; i++)
cin >> a[i];
for (int i=1; i<=n; i++)
{
if (a[i-1]<=a[i])
b[i]=b[i-1]+(a[i]-a[i-1])/d;
else
b[i]=b[i-1]-(a[i-1]-a[i]-1)/d-1;
}
for (int i=1; i<=n; i++)
c[i]=c[i-1]+b[i];
for (int i=n; i>=1; i--)
{
while (s.size() && b[i]<b[s.top()])
{
ind[s.top()][0]=i;
cost[s.top()][0]=c[s.top()]-c[i]-b[s.top()]*(s.top()-i);
s.pop();
}
s.push(i);
}
for (int i=1; i<20; i++)
{
for (int j=1; j<=n; j++)
{
ind[j][i]=ind[ind[j][i-1]][i-1];
cost[j][i]=cost[j][i-1]+cost[ind[j][i-1]][i-1];
}
}
cin >> q;
for (int i=1; i<=q; i++)
{
int l, r, ans=0;
cin >> l >> r;
for (int j=19; j>=0; j--)
{
if (ind[r][j]>=l)
{
ans+=cost[r][j];
r=ind[r][j];
}
}
cout << (b[r]<0?-1:ans+c[r]-c[l-1]-b[r]*(r-l+1)) << '\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... |