网址:https://codeforces.ml/contest/1333/problem/C
题目描述:
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.
Input
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
Output a single integer — the number of good subarrays of a.
Examples
input
3
1 2 -3
output
5
input
3
41 -41 41
output
3
Note
In the first sample, the following subarrays are good: [1], [1,2], [2], [2,−3], [−3]. However, the subarray [1,2,−3] isn't good, as its subarray [1,2,−3] has sum of elements equal to 0.
In the second sample, three subarrays of size 1 are the only good subarrays. At the same time, the subarray [41,−41,41] isn't good, as its subarray [41,−41] has sum of elements equal to 0.
题解:对于一个数组a要想找到他所有子数组,只需要从数组a第一个元素开始一直遍历到最后一个元素,每次遍历是从当前元素向前(此元素之前的元素)看。
这道题就是利用sum(前i个元素之和),使用了map数据结构,map[sum]=i。准确的说是每此遍历找到以a[i]为最后一个元素的good的子数组。
这里比较重要的就是变量pos(在后面的代码中),理解了pos就可以。
AC代码:
#include<iostream>
#include<cstdio>
#include<map>
#define ll long long int
using namespace std;
int main(){
ll n,sum=0,a,ans=0,pos=-1;
cin>>n;
map<ll,ll>mp;
mp[0]=0;
for(int i=1;i<=n;i++){
cin>>a;
sum+=a;
if(mp.find(sum)!=mp.end()){//存在sum
pos=max(pos,mp[sum]);
}
mp[sum]=i;
ans=ans+i-pos-1;
}
cout<<ans<<endl;
return 0;
}
注:碰到了许多的算法题基本都是数学题,但有时数学逻辑是真的想不到,即便是别人稍微一提及自己就能明白,但做的时候自己想着实没有想到。应该还是不熟练所致。