#include <bits/stdc++.h>
using namespace std;
#define forn(i,n) for(int i=0;i<int(n);i++)
#define forsn(i,s,n) for(int i=int(s);i<int(n);i++)
#define dforn(i,n) for(int i=int(n)-1;i>=0;i--)
#define dforsn(i,s,n) for(int i=int(n)-1;i>=int(s);i--)
#define fst first
#define snd second
#define pb push_back
#define eb emplace_back
#define sz(x) (int)x.size()
#define all(x) x.begin(), x.end()
typedef long long ll;
typedef vector<ll> vll;
typedef vector<int> vi;
typedef pair<int,int> ii;
const ll INF=1e18;
struct Node{
bool flag=false;
ll mini=INF,maxi=-INF;
int cnt=0;
ll cost=0;
Node(){
flag=true;
}
Node(ll x){
cnt=1;
mini=maxi=x;
cost=0;
flag=false;
}
};
ll d;
Node merge(Node &a, Node &b){
if(a.flag) return b;
if(b.flag) return a;
Node c;
ll diff=a.maxi-b.mini;
ll k=max((diff+d-1)/d,0LL);
c.maxi=b.maxi;
assert(a.maxi-d*k<=b.mini);
c.mini=a.mini-d*k;
c.cnt=a.cnt+b.cnt;
c.cost=a.cost+b.cost+k*a.cnt;
c.flag=false;
return c;
}
const int SZ=1<<19;
Node st[2*SZ];
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
int n;
cin>>n>>d;
vll c(n);
forn(i,n){
cin>>c[i];
st[i+SZ]=c[i];
}
dforsn(i,1,SZ){
st[i]=merge(st[2*i],st[2*i+1]);
}
int q;
cin>>q;
forn(_,q){
Node left,right;
int l,r;
cin>>l>>r;
for(l+=SZ-1,r+=SZ;l<r;l/=2,r/=2){
if(l&1) left=merge(left,st[l++]);
if(r&1) right=merge(st[--r],right);
}
Node ret=merge(left,right);
if(ret.mini<0) cout<<"-1\n";
else cout<<ret.cost<<'\n';
}
return 0;
}
# | 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... |