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

本文介绍了一种高效解决子数组求和问题的方法,通过维护前缀和与使用尺取算法,避免了暴力枚举子数组的复杂度,实现了快速找出所有满足任意子数组之和均不为0的子数组数量。

题目链接:点击查看

题目大意:给出一个长度为 n 的数组 a,抛出 good 数组的定义:

  1. good 数组为数组 a 的一个子数组
  2. good 数组的任意子数组之和均不为 0

(注意区分子数组和子数列的区别)

题目分析:首先是常识,对于一个长度为 n 的数组而言,有 n * ( n + 1 ) / 2 个子数组,有 n * ( n + 1 ) / 2 - 1 个非空子数组

其次分析数据范围,n 高达 2e5,所以肯定不能暴力 n * n 去枚举每一个子数组判断

因为子数组是连续的一段数组,加上题目将子数组之和作为判断条件,提示到这里不难想到可以维护一个前缀和 sum 方便后续操作

然后是加上一小点思维,稍微想一下不难发现,一个 good 数组如果想要满足任意子数组之和均不为 0 ,那么这段 good 数组所对应的前缀和的值不能有重复,换句话说,如果数组 a 中的 [ l , r ] 这段为 good 数组,那么 sum[ i ] != sum[ j ] ,i , j ∈ [ l , r ] 

思考到这里不难想到尺取了,现在还差一点,那就是如何维护答案,因为尺取可以维护出最长的那段 good 数组,所以我们可以在实现尺取时,每次都将 r 指针向右移动一个单位,根据条件维护 l 指针的位置,此时新出现的 good 数组有

  1. a[ l + 1 ] ~ a[ r ] 
  2. a[ l + 2 ] ~ a[ r ]
  3. ......
  4. a[ r ] ~ a[ r ]

为了方便实现,l 代表的是当前 good 数组左端点的前一个点,r 代表的自然是当前 good 数组的右端点了

代码的实现意外的简单。。

代码:

#include<iostream>
#include<cstdio>
#include<string>
#include<ctime>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<stack>
#include<climits>
#include<queue>
#include<map>
#include<set>
#include<sstream>
#include<unordered_map>
using namespace std;

typedef long long LL;

typedef unsigned long long ull;

const int inf=0x3f3f3f3f;

const int N=2e5+100;

map<LL,bool>vis;
 
LL sum[N];

int main()
{
#ifndef ONLINE_JUDGE
//	freopen("input.txt","r",stdin);
//	freopen("output.txt","w",stdout);
#endif
//	ios::sync_with_stdio(false);
	int n;
	scanf("%d",&n);
	vis[0]=true;//sum[0]=0
	for(int i=1;i<=n;i++)
	{
		int num;
		scanf("%d",&num);
		sum[i]=sum[i-1]+num;
	}
	LL ans=0;
	int l=0,r=1;
	while(r<=n)
	{
		while(vis[sum[r]])
		{
			vis[sum[l]]=false;
			l++;
		}
		vis[sum[r]]=true;
		ans+=r-l;
		r++;
	}
	printf("%lld\n",ans);
	
	
	










    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Frozen_Guardian

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

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

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

打赏作者

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

抵扣说明:

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

余额充值