Codeforces Round #674 (Div. 3)D. Non-zero Segments【前缀和+思维】

这是一个关于数组处理的问题,目标是通过插入任意整数确保任何连续子序列的和不为零。输入是一个不含零的整数数组,输出是最少需要插入的整数数量。解决方案是检查前缀和是否存在重复,若存在则需插入一个数来改变和。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

传送门
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();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值