CF1428F Fruit Sequences

Solution- CF 1428 F \mathrm{CF1428F}CF1428F

Topic meaning

Topic portal

S o l \mathrm{Sol} Sol

Consider for each 1 11 Count the contribution alone.

Hypothesis ai = 1 a_i = 1ai=1 then the consecutive1 1ending with itThe length of 1 islll , then in[1, i − l] [1,il][1,il ] find the farthestjjj satisfiesaj = 1 a_j=1aj=1 and starting with it1 1The length of 1 segmentL ≤ l L\leq lLl . We can use the line segment tree to maintain the intervalmax ⁡ \maxmax mark to achieve easy.

Suppose we found jjj considers how to join the contribution, obviously[j, i − l] [j,il][j,il ] The contribution of this interval should be addedlll [ i − l + 1 , i ] [i-l+1,i] [il+1,i ] Add1 1 tothis interval as a whole1 (each subscriptiii as an individual).

In this way, we only need to maintain the interval plus, interval max ⁡ \maxmax will do. Time complexityO (n log ⁡ n) O(n\log n)O ( nlogn)

C o d e \mathrm{Code} Code

const int N=5e5+5;

int n,m,tr[N*4],laz[N*4],tr2[N*4],tag[N*4];
int ans,las;
char a[N];

inline void pd(int x,int l,int r,int t1,int t2) 
{
    
    
	if(t1) tag[x]=0,tr[x]=(r-l+1)*t1,tr2[x]=laz[x]=t1;
	if(t2) tr[x]+=(r-l+1)*t2,tag[x]+=t2,tr2[x]+=t2; 
}

inline void pushdown(int x,int l,int r) 
{
    
    
	if(laz[x]||tag[x]) 
	{
    
    
		int mid=l+r>>1;
		pd(x<<1,l,mid,laz[x],tag[x]);
		pd(x<<1|1,mid+1,r,laz[x],tag[x]);
		laz[x]=tag[x]=0;
	}
}

inline int query(int x,int l,int r,int goal) 
{
    
    
	if(l==r) return l;
	int mid=l+r>>1;
	pushdown(x,l,r);
	if(tr2[x<<1|1]>=goal) return query(x<<1|1,mid+1,r,goal);
	else return query(x<<1,l,mid,goal);
}

inline void add(int x,int l,int r,int ll,int rr,int v) 
{
    
    
	if(ll>r||rr<l) return;
	if(ll<=l&&r<=rr) 
	{
    
    
		tr[x]+=(r-l+1)*v,tag[x]+=v,tr2[x]+=v;
		return;
	}
	int mid=l+r>>1;
	pushdown(x,l,r);
	add(x<<1,l,mid,ll,rr,v),add(x<<1|1,mid+1,r,ll,rr,v);
	tr[x]=tr[x<<1]+tr[x<<1|1];
	tr2[x]=max(tr2[x<<1],tr2[x<<1|1]);
}

inline void Add(int x,int l,int r,int ll,int rr,int v) 
{
    
    
	if(ll>r||rr<l) return;
	if(ll<=l&&r<=rr)
	{
    
    
		tr[x]=(r-l+1)*v,tr2[x]=v,laz[x]=v;
		tag[x]=0;
		return;
	}
	int mid=l+r>>1;
	pushdown(x,l,r);
	Add(x<<1,l,mid,ll,rr,v),Add(x<<1|1,mid+1,r,ll,rr,v);
	tr[x]=tr[x<<1]+tr[x<<1|1];
	tr2[x]=max(tr2[x<<1],tr2[x<<1|1]);
}

signed main()
{
    
    
	scanf("%d",&n);
	scanf("%s",a+1);
	For(i,1,n) 
	{
    
    
		if(a[i]=='1') 
		{
    
    
			if(!las) las=i;
			int can_reach=query(1,1,n,i-las+1); 
			add(1,1,n,las,i,1);
			if(can_reach<las) Add(1,1,n,can_reach,las-1,i-las+1);
		}
		else las=0;
		ans+=tr[1];
	}
	io.write(ans),puts("");
	return 0;
}

Guess you like

Origin blog.csdn.net/wangyiyang2/article/details/109147002