#include <bits/stdc++.h>
using namespace std;
#define sz(x) (int)x.size()
#define all(x) x.begin() , x.end()
const int SQRT = 632;
void solve(){
int n;
cin >> n;
int arr[n];
for(int i = 0;i<n;i++)cin >> arr[i];
long long pre[n+1];
pre[0] = 0;
for(int i = 0;i<n;i++){
pre[i+1] = pre[i] + arr[i];
}
map<long long,int>mpa;
int nxt[n+1];
fill(nxt , nxt + n+1 , n+1);
for(int i = n;i>=0;i--){
if(mpa.count(pre[i])){
nxt[i] = mpa[pre[i]];
}
mpa[pre[i]] = i;
}
// cout << "nxt : ";for(int i = 0;i<=n;i++)cout << nxt[i] << " ";cout << endl;
vector<int>tree[n+2] , path;
multiset<int>ste;
for(int i = 0;i<=n;i++)ste.insert(nxt[i]);
for(int i = 0;i<=n;i++){
// cout << *ste.begin() << " -> " << i << endl;
tree[*ste.begin()].push_back(i);
ste.erase(ste.find(nxt[i]));
}
// cout << "done" << endl;
int jump1[n+1] , jump2[n+1];
memset(jump1 , -1 , sizeof(jump1));
memset(jump2 , -1 , sizeof(jump2));
function<void(int)> dfs = [&](int node){
if(!path.empty()){
jump1[node] = path.back();
}
if(sz(path) - SQRT >= 0){
jump2[node] = path[sz(path) - SQRT];
}
path.push_back(node);
for(auto itr : tree[node]){
dfs(itr);
}
path.pop_back();
};
dfs(n+1);
// cout << "jump1 : ";for(int i = 0;i<=n;i++)cout << jump1[i] << " ";cout << endl;
// cout << "jump2 : ";for(int i = 0;i<=n;i++)cout << jump2[i] << " ";cout << endl;
int q;
cin >> q;
while(q--){
int l,r;
cin >> l >> r;
l--;
int ans = 0;
// cout << "query : " << l << " " << r << endl;
while(l <= n and jump2[l] <= r and jump2[l] != -1){
ans += SQRT;
l = jump2[l];
}
// cout << "ans : " << ans << endl;
// cout << "query : " << l << " " << r << endl;
while(l <= n and jump1[l] <= r and jump1[l] != -1){
ans++;
l = jump1[l];
}
// cout << "ans : " << ans << endl;
cout << ans << '\n';
// cout << endl;
}
}
signed main(){
ios_base::sync_with_stdio(0);cin.tie(0);
int testcase=1;//cin >> testcase;
while(testcase--)solve();
cerr << 1000.0 * clock() / CLOCKS_PER_SEC << " ms" << endl;
}
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |