题目
传送门
Kolya got an integer array a1,a2,…,an. The array can contain both positive and negative integers, but Kolya doesn’t like 0, so the array doesn’t contain any zeros.
Kolya doesn’t like that the sum of some subsegments of his array can be 0. The subsegment is some consecutive segment of elements of the array.
You have to help Kolya and change his array in such a way that it doesn’t contain any subsegments with the sum 0. To reach this goal, you can insert any integers between any pair of adjacent elements of the array (integers can be really any: positive, negative, 0, any by absolute value, even such a huge that they can’t be represented in most standard programming languages).
Your task is to find the minimum number of integers you have to insert into Kolya’s array in such a way that the resulting array doesn’t contain any subsegments with the sum 0.
Input
The first line of the input contains one integer n (2≤n≤200000) — the number of elements in Kolya’s array.
The second line of the input contains n integers a1,a2,…,an (−109≤ai≤109,ai≠0) — the description of Kolya’s array.
Output
Print the minimum number of integers you have to insert into Kolya’s array in such a way that the resulting array doesn’t contain any subsegments with the sum 0.
input
4
1 -5 3 2
output
1
input
5
4 -2 3 -9 2
output
0
input
9
-1 1 -1 1 -1 1 1 -1 -1
output
6
input
8
16 -5 -11 -15 10 5 4 -4
output
3
题意:给出一个有n个数的数组,我们可以在他的任意位置插入一个无穷大的的数使他的每个连续子序列和都不能为零,问至少要插入几个数?
思路:如果出现连续子序列的和为零的情况他的前缀和中一定会出现相同的数,我们只要判断是否出现相同的数即可,具体看代码.
AC code
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<map>
#include<sstream>
#include<queue>
#include<stack>
using namespace std;
#define ll long long
map<ll,ll>m;//判断是否有相同的数出现过
int n;
void solve()
{
ll x,sum=0,ans=0;
m.clear();
m[0]=1;//可能有以第一个数开头的子序列和为零的情况
for(int i=0;i<n;i++)
{
cin>>x;
sum+=x;
if(m[sum])//如果出现相同的数我们就在这个数前面插入一个数,此时这个数还能被利用
{
ans++;
m.clear();//前面的数都不能用
m[0]=1;
sum=x;
m[sum]=1;
}
else m[sum]=1;
}
printf("%lld\n",ans);
}
int main()
{
cin>>n;
solve();
}