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.
题意:找出一串数中,连续多个数和为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;
}