Codeforces1426D题解

问题描述

D. Non-zero Segments
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
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.

Examples
inputCopy
4
1 -5 3 2
outputCopy
1
inputCopy
5
4 -2 3 -9 2
outputCopy
0
inputCopy
9
-1 1 -1 1 -1 1 1 -1 -1
outputCopy
6
inputCopy
8
16 -5 -11 -15 10 5 4 -4
outputCopy
3

大意

给你一个数列,目标是用最小操作次数(加数字)使得数列任意字段和不为0。每次操作可以加任意数量的任意数字。

题解

子段和为零等价于prefix[r]==prefix[l-1],所以每次读数的时候就用set存一下前缀和(任意时刻必须保证set里有存0),当遇到前缀和相等的情况时,说明存在和为0的子段,就在这个数字前面加一个超大的整数(代码里不用写这个),代码实现方法就是清空set(因为加入新数字后子段和发生了改变,后续的prefix一定更大),然后以这个元素为起点,算新的前缀和,按照上述方法继续判断。记得每次清空后要重新加入0和起点元素。

代码

#include<bits/stdc++.h>
#define ll long long 
#define pb push_back
using namespace std;
int main(){
	int n,x;
	set<ll> s;
	vector<ll> a;
	ll p[200005],ans=0;
	memset(p,0,sizeof(p));
	cin>>n; s.insert(0);
	for (int i=1; i<=n; i++){
		cin>>x; 
		p[i]=p[i-1]+x;
	    if (s.find(p[i])==s.end())
	        s.insert(p[i]);
	    else{
	    	ans++;  s.clear(); p[i]=x; s.insert(0); s.insert(x);
		}
	}
	cout<<ans<<endl;
	return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值