AtCoder Grand Contest 023 A - Zero-Sum Ranges

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.


题意:找出一串数中,连续多个数和为0的区间右多少个。

题解:我真的想了好久都不会,然后被一个学长一眼秒,我果然还是太菜了。如果直接暴力的话会超时。这题要用到前缀和(前n个数的和),然后当有n个前缀和相等且他们的位置不相等的时候,就有C(n,2)个区间的和为0,用map来存前缀和的值的个数。然后遍历map,求解。

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

const int maxn = 2e5 + 5;

long long s[maxn],a[maxn];
long long sum,x,ans,n,j,y;

int main()
{
    while(scanf("%lld",&n) != EOF)
    {
        map<long long,long long> q;
        sum = 0;
        j = 0;
        ans = 0;
        for(int i = 1;i <= n;i++)
        {
            scanf("%lld",&a[i]);
            sum += a[i];
            s[++j] = sum;
            q[sum]++;
        }
        for(int i = 1;i <= j;i++)
        {
            x = s[i];
            y = q[x];
            if(x == 0) ans++;
            ans += y * (y - 1) / 2;
            q[x] = 1;
        }
        printf("%lld\n",ans);
    }
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值