Coddforces Eugene and an array

题目链接

题目让你找出一个数组的 nonempty array (题目中要求从前面或者结尾删除去若干个数且不为空) ,只要这个数组中部分的元素之和为0那么这个得到的数组就不是完美的的(也就是不符合答案的),现在我们只需要找到连续子段和为0的序列,找到起点 st 和终点 ed ,那么答案就是两边可选择的方案数相乘(st-1+1)(n-ed+1) ,为了避免重复,可以记录一下上一个和为0的点的位置,以它为向左的方案数的终点即可,因为再向左的方案已经被上一个和为0的数组计算过了

如何找和为0的子序列呢?可以记录下前缀和,当前的缀和与前面相等的时候,那么就出现了和为0的序列,比如说 4 1 2 -3,发现a[1]=a[4]=4,那么起点就是2,终点就是4,终点很好找,就是当前枚举到的 i ,起点可以用mp存每个前缀和数值的下标,可以用 mp[4]=1 找到st-1,算出答案即可。

还要注意下算sum的时候转一下 LL ,比赛debug心态爆炸,找了半天逻辑的错结果发现是没转 LL ,以为sum开了 LL 就万事大吉了。

#include<cstdio>
#include<iostream>
#include<string>
#include<cstring>
#include<map>
#include<cmath>
#include<cctype>
#include<vector>
#include<set>
#include<queue>
#include<algorithm>
#include<sstream>
#define X first
#define Y second
using namespace std;

typedef long long LL;
typedef pair<int,int> PII;

const int N=200110,mod=1e9+7,INF=0x3f3f3f3f;
const double eps=1e-6;

int n;
int a[N];
LL pre[N],ans;
map<LL,int>mp;

int main()
{
//	ios::sync_with_stdio(false);
//	cin.tie(0);
	
	scanf("%d",&n);
	
	for(int i=1;i<=n;i++)
		scanf("%d",&a[i]),pre[i]=pre[i-1]+a[i];
	
	mp[0]=0;
	int st=-1,ed=-1;
	
	for(int i=1;i<=n;i++)
	{
		LL t=pre[i];
		if(!mp.count(t))
		{
			mp[t]=i;
			continue;
		}

		if(st==-1&&ed==-1)
		{
			st=mp[t]+1,ed=i;
			ans+=(LL)(n-i+1)*(LL)(mp[t]+1);
		}
		else 
		{
			if(mp[t]>=st) 
			{
				ans+=(LL)(mp[t]-st+1)*(LL)(n-i+1);
				st=mp[t]+1,ed=i;
			}
		}

		mp[t]=i;
	}	
	
	LL sum=(LL)n*(n+1)/2;
	
	printf("%lld\n",sum-ans);





	return 0;
}










发布了43 篇原创文章 · 获赞 1 · 访问量 1564

猜你喜欢

转载自blog.csdn.net/DaNIelLAk/article/details/105402017
今日推荐