CF1333 C. Eugene and an array

C. Eugene and an array

题意

给你一个长度为n的数组,求不含和为0的子串的个数。

思路

前缀和 思维
前缀和 p r e [ i ] = p r e [ j ] pre[i]=pre[j] 意味着 a i + 1 a j a_{i+1} \sim a_j 这一段的和为0,则所求字符串不应该包含这段,令 p p p r e [ i ] pre[i] 所在的位置,则不包含子串和为0的个数为 i ( p + 1 ) i-(p+1)
初始化 p o s [ 0 ] = 0 pos[0]=0

map.count(key) 返回值为bool型,表示是否存在key。

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;

ll n,q,s,ans;
map<ll,ll> pos;

int main(){
	ios::sync_with_stdio(false);
	cin.tie(0);
	cin>>n;
	pos[0]=0;
	ll q=-1;
	for(int i=1;i<=n;i++){
		ll x;cin>>x;
		s+=x;
		if(pos.count(s)) q=max(q,pos[s]);
		ans+=i-q-1;
		pos[s]=i;
	}
	cout<<ans<<'\n';
	return 0;
}
发布了78 篇原创文章 · 获赞 10 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Meulsama/article/details/105411558
今日推荐