#include <bits/stdc++.h>
#pragma GCC optimize("O3")
// #define int long long
#define ll long long
#define se second
#define fi first
#define pb push_back
#define lf (id<<1)
#define rg ((id<<1)|1)
#define md ((l+r)>>1)
using namespace std;
typedef pair<int,int> pii;
typedef pair<pii,pii> ipii;
const int MAXN = 4e5+2;
const int LOG = 8;
int n, pr[MAXN], q;
int anc[MAXN][LOG];
vector<pii> vec;
int te[MAXN];
signed main(){
ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
cin>>n;
for(int i=1; i<=n; i++){
int a; cin>>a; pr[i] = pr[i-1]+a;
vec.pb({pr[i], i});
}
vec.pb({0, 0});
sort(vec.begin(), vec.end());
for(int i=1; i<=n+1; i++) te[i] = n+1;
for(int i=0; i<n; i++){
if(i!=0 && vec[i].fi == vec[i-1].fi){
int id = vec[i-1].se+1;
te[ id ] = min(te[ id ], vec[i].se);
}
// cout << "don\n";
}
int mn = n+1; anc[n+1][0] = n+1;
for(int i=n; i>=1; i--){
mn = min(mn, te[i]);
// cout << i << ' ' << mn << " mn\n";
anc[i][0] = mn;
}
for(short int j=1; j<LOG; j++){
for(int i=1; i<=n+1; i++){
if(anc[i][j-1] >= n){
anc[i][j] = n+1; continue;
}
anc[i][j] = anc[ anc[i][j-1]+1 ][j-1];
}
}
cin>>q;
for(; q; q--){
int a, b; cin>>a>>b;
// lift sampe kurang dari r
int tot = 0, nw = a;
// cout << idx<<' '<<nw << " idx\n";
for(short int j=LOG-1; j>=0; j--){
for(; anc[nw][j] <= b; ){
// cout << nw << ' ' << anc[nw][j] << " anc\n";
nw = anc[nw][j]+1; tot += (1<<j);
}
}
cout << tot << '\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... |