This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define pb push_back
#define fr first
#define sc second
#define int ll
#define all(x) x.begin(),x.end()
#define rall(x) x.rbegin(),x.rend()
const int N=3e5+5,INF=1e18;
int t[4*N],lazy[4*N];
void push(int x, int l, int r) {
if( lazy[x] == INF ) return;
t[x] = lazy[x] * (r - l + 1);
if( l < r ) {
lazy[2 * x] = lazy[x];
lazy[2 * x + 1] = lazy[x];
}
lazy[x] = INF;
}
void update(int lx, int rx, int v, int x, int l, int r) {
push( x, l, r );
if( lx>r || rx<l ) return;
if( lx <= l && r <= rx) {
lazy[x]=v;
push(x, l, r);
return;
}
int md = ( l + r ) / 2;
update( lx, rx, v, 2 * x, l, md );
update( lx, rx, v, 2 * x + 1, md + 1, r );
t[x] = t[2 * x] + t[2 * x + 1];
}
int query( int lx, int rx, int x, int l, int r ) {
push( x, l, r );
if( lx > r || rx < l ) return 0;
if( lx <= l && r <= rx ) return t[x];
int md = ( l + r ) / 2;
return query( lx, rx, 2 * x, l, md ) + query( lx, rx, 2 * x + 1, md + 1, r );
}
vector<pair<int,int>> Q[N];
int a[N],need[N],pref[N];
int s[N],pr[N],v[N];
void solve() {
int n,d;cin>>n>>d;
for(int i=1;i<=n;i++) cin>>a[i];
for(int i=1;i<=n;i++) {
v[i] = a[i]/d;
pr[i] = pr[i-1]+v[i];
}
for( int i = 2; i <= n; i++ ) {
need[i]=need[i-1];
if( (a[i-1]%d) > (a[i]%d) ) need[i]++;
s[i] = need[i]+s[i-1];
}
int q;cin>>q;
for(int i=0;i<q;i++) {
int l,r;cin>>l>>r;
Q[r].pb({l,i});
}
for(int i=0;i<4*N;i++) lazy[i]=INF;
stack<pair<int,int>> st;
vector<int> ans(q);
for(int i=1;i<=n;i++) {
int id = i;
while(!st.empty() && st.top().fr>v[i]-need[i]) {
id = st.top().sc;
st.pop();
}
st.push({v[i] - need[i], id});
update(id, i, v[i] - need[i], 1, 1, n);
for( auto it : Q[i] ) {
ans[it.sc] = ( pr[i] - pr[it.fr - 1] );
ans[it.sc] -= query( it.fr, i, 1, 1 , n);
ans[it.sc] -= ( s[i] - s[it.fr - 1] );
if( query (it.fr, it.fr, 1,1,n) + need[it.fr] < 0) ans[it.sc] = -1;
}
}
for(int i=0;i<q;i++) cout<<ans[i]<<'\n';
}
signed main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
int t=1;//cin>>t;
while(t--){
solve();
}
}
//#endif
# | 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... |