题目链接
Eugene likes working with arrays. And today he needs your help in solving one challenging task.
An array c is a subarray of an array b if c can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
Let’s call a nonempty array good if for every nonempty subarray of this array, sum of the elements of this subarray is nonzero. For example, array [−1,2,−3] is good, as all arrays [−1], [−1,2], [−1,2,−3], [2], [2,−3], [−3] have nonzero sums of elements. However, array [−1,2,−1,−3] isn’t good, as his subarray [−1,2,−1] has sum of elements equal to 0.
Help Eugene to calculate the number of nonempty good subarrays of a given array a.
The first line of the input contains a single integer n (1≤n≤2×105) — the length of array a.
The second line of the input contains n integers a1,a2,…,an (−109≤ai≤109) — the elements of a.
Output a single integer — the number of good subarrays of a.
3
1 2 -3
5
3
41 -41 41
3
一开始考虑用总情况去减,后来发现比较麻烦,因为会存在前缀和与数都为0的情况,不好判断,改成累加答案~
用 m a p map map 更新前缀和 s u m sum sum 的位置,对当前前缀和 s u m sum sum, a n s = a n s + i − m [ s u m ] ans=ans+i-m[sum] ans=ans+i−m[sum],注意前缀和为 0 0 0 时, a n s ans ans 要少加一个1,即 m [ 0 ] = 1 m[0]=1 m[0]=1,AC代码如下:
#include
typedef long long ll;
using namespace std;
ll n,k,sum=0,pos=0,ans=0;
map<ll,ll> m;
int main()
{
cin>>n;
m[0]=1;
for(ll i=1;i<=n;i++)
{
cin>>k;
sum+=k;
pos=max(pos,m[sum]);
ans+=i-pos;
m[sum]=i+1;
}
cout<<ans;
}