Submission #1365724

#TimeUsernameProblemLanguageResultExecution timeMemory
1365724namhhSum Zero (RMI20_sumzero)C++20
0 / 100
1095 ms840 KiB
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define pii pair<int,int>
#define fi first
#define se second
const int N = 4e5+5;
const int lg = 10;
int n,q,a[N],st[N][lg],nxt[N];
ll pre[N];
map<ll,int>mp;
void build(){
	for(int j = 1; j < lg; j++){
		for(int i = 1; i <= n; i++){
			if(st[i][j-1] == n+2) st[i][j] = n+2;
			else st[i][j] = st[st[i][j-1]][j-1];
		}
	}
}
int query(int l, int r){
	int sum = 0;
	for(int i = lg-1; i >= 0; i--){
		if(l < st[l][i] && st[l][i] <= r+1){
			sum += (1 << i);
			l = st[l][i];
		}
	}
	return sum;
}
signed main(){
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cin >> n;
	for(int i = 1; i <= n; i++){
		cin >> a[i];
		pre[i] = pre[i-1]+a[i];
	}
	for(int i = n; i >= 1; i--){
		mp[pre[i]] = i;
		if(mp.count(pre[i-1])) nxt[i] = mp[pre[i-1]];
		else nxt[i] = n+1;
	}
	mp.clear();
	nxt[n+1] = n+1;
	for(int i = n; i >= 1; i--) nxt[i] = min(nxt[i],nxt[i+1]);
	//for(int i = 1; i <= n; i++) cout << nxt[i] << "\n";
	for(int i = 1; i <= n; i++) st[i][0] = nxt[i]+1;
	build();
//	for(int j = 1; j < lg; j++){
//		for(int i = 1; i <= n; i++) cout << i << " " << j << " " << st[i][j] << "\n";
//	}
	cin >> q;
	while(q--){
		int l,r;
		cin >> l >> r;
		int res = 0;
		while(true){
			int sum = 0;
			for(int i = lg-1; i >= 0; i--){
				if(st[l][i] <= r+1){
					sum += (1 << i);
					l = st[l][i];
				}
			}
			res += sum;
			if(sum == 0) break;
		}
		cout << res << "\n";
	}
}
#Result Execution timeMemoryGrader output
Fetching results...
#Result Execution timeMemoryGrader output
Fetching results...
#Result Execution timeMemoryGrader output
Fetching results...