Atcoder Grand contest 023

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

  • 1N2×105
  • −109Ai109
  • 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

Copy
6
1 3 -4 2 2 -2

Sample Output 1

Copy
3

There are three contiguous subsequences whose sums are 0: (1,3,4), (−4,2,2) and (2,2).


Sample Input 2

Copy
7
1 -1 1 -1 1 -1 1

Sample Output 2

Copy
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

Copy
5
1 -2 3 -4 5

Sample Output 3

Copy
0

There are no contiguous subsequences whose sums are 0.


 
  1. #include <iostream>
  2. #include <cstdio>
  3. #include <cstdlib>
  4. #include <cstring>
  5. #include <algorithm>
  6. #include <map>
  7.  
  8. using namespace std;
  9. long long sum,a,N,ans;
  10.  
  11. int main()
  12. {
  13. map<long long,long long>ms;//用于标记部分和出现的次数
  14. ms[0]++;//注意这里0要提前加1
  15. long long i;
  16. sum=0;
  17. ans=0;
  18. scanf("%lld",&N);
  19. for(i=0;i<N;i++){
  20. scanf("%lld",&a);
  21. sum=sum+a;
  22. ans=ans+ms[sum];//如果这个和,在之前出现过,那么说明有存在和为0的子序列(不然怎么重复出现呢)
  23. ms[sum]++;
  24. }
  25. printf("%lld\n",ans);
  26. return 0;
  27. }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值