Eugene and an array CodeForces - 1333C(尺取法)

Eugene likes working with arrays. And today he needs your help in solving one challenging task.

An array c is a subarray of an array b if c can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.

Let’s call a nonempty array good if for every nonempty subarray of this array, sum of the elements of this subarray is nonzero. For example, array [−1,2,−3] is good, as all arrays [−1], [−1,2], [−1,2,−3], [2], [2,−3], [−3] have nonzero sums of elements. However, array [−1,2,−1,−3] isn’t good, as his subarray [−1,2,−1] has sum of elements equal to 0.

Help Eugene to calculate the number of nonempty good subarrays of a given array a.

Input
The first line of the input contains a single integer n (1≤n≤2×105) — the length of array a.

The second line of the input contains n integers a1,a2,…,an (−109≤ai≤109) — the elements of a.

Output
Output a single integer — the number of good subarrays of a.

Examples
Input
3
1 2 -3
Output
5
Input
3
41 -41 41
Output
3
Note
In the first sample, the following subarrays are good: [1], [1,2], [2], [2,−3], [−3]. However, the subarray [1,2,−3] isn’t good, as its subarray [1,2,−3] has sum of elements equal to 0.

In the second sample, three subarrays of size 1 are the only good subarrays. At the same time, the subarray [41,−41,41] isn’t good, as its subarray [41,−41] has sum of elements equal to 0.
尺取的题目还是一样的不会,搞了好久。。。
思路:维护一个前缀和应该是挺好想到的。但是关键问题是怎么有序不重复的维护good序列。盲目的去做很容易漏掉一些东西或者重复计算一些东西。最暴力的做法是什么?就是两重循环遍历去找,但是那样的话,时间是不允许的。有一个性质,对于一个区间[l,r],这个区间里都是good序列的条件是:前缀数组在[l,r]中没有重复的值,例如,如果sum[i]=x,sum[j]也等于x的话,就说明sum[i+1]+sum[i+2]+…sum[j]=0。这样的话问题就转化成,对于一个右端点R,如何找到最小的左端点L,使得[L,R]中没有重复值。这个时候就很容易就想到尺取法了。假如当前右端点的sum值出现过,那么我们找到上一次出现这个值的下一个位置,从这个位置到当前右端点的位置就肯定没有非good序列了,ans加上这一段区间的长度,就代表这一段区间的good序列的数量了。
代码如下:

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

const int maxx=2e5+100;
int a[maxx];
ll sum[maxx];
int n;

int main()
{
	scanf("%d",&n);
	memset(sum,0,sizeof(sum));
	for(int i=1;i<=n;i++)
	{
		scanf("%d",&a[i]);
		sum[i]=sum[i-1]+a[i];
	}
	map<ll,bool> mp;
	mp.clear();
	int l=0,r=1;
	ll ans=0;
	mp[0]=1;
	while(r<=n)
	{
		while(mp[sum[r]])
		{
			mp[sum[l++]]=0;
		}
		mp[sum[r]]=1;
		ans+=(r-l);
		r++;
	}
	printf("%lld\n",ans);
	return 0;
}

努力加油a啊,(o)/~

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

starlet_kiss

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值