A - Zero-Sum Ranges
Time limit : 2sec / Memory limit : 256MB
Score : 200 points
Problem Statement
We have an integer sequence A, whose length is N.
Find the number of the non-empty contiguous subsequences of A whose sums are 0.Note that we are counting the ways to take out subsequences.That is, even if the contents of some two subsequences are the same, they are counted individually if they are taken from different positions.
Constraints
- 1≤N≤2×105
- −109≤Ai≤109
- All values in input are integers.
Input
Input is given from Standard Input in the following format:
N A1 A2 … AN
Output
Find the number of the non-empty contiguous subsequences of A whose sum is 0.
Sample Input 1
6 1 3 -4 2 2 -2
Sample Output 1
3
There are three contiguous subsequences whose sums are 0: (1,3,−4), (−4,2,2) and (2,−2).
Sample Input 2
7 1 -1 1 -1 1 -1 1
Sample Output 2
12
In this case, some subsequences that have the same contents but are taken from different positions are counted individually.For example, three occurrences of (1,−1) are counted.
Sample Input 3
5 1 -2 3 -4 5
Sample Output 3
0
There are no contiguous subsequences whose sums are 0.
- #include <iostream>
- #include <cstdio>
- #include <cstdlib>
- #include <cstring>
- #include <algorithm>
- #include <map>
- using namespace std;
- long long sum,a,N,ans;
- int main()
- {
- map<long long,long long>ms;//用于标记部分和出现的次数
- ms[0]++;//注意这里0要提前加1
- long long i;
- sum=0;
- ans=0;
- scanf("%lld",&N);
- for(i=0;i<N;i++){
- scanf("%lld",&a);
- sum=sum+a;
- ans=ans+ms[sum];//如果这个和,在之前出现过,那么说明有存在和为0的子序列(不然怎么重复出现呢)
- ms[sum]++;
- }
- printf("%lld\n",ans);
- return 0;
- }