Codeforces Round # 603 (Div. 2) E. Editor (segment tree thinking +)

Topic Link
Here Insert Picture Description
Here Insert Picture Description
meaning of the questions: hate this stinking long title. . . Is simply a given string, L represents a cursor left, R represents a shift there, you ask the maximum number of nested parentheses.
Idea: You can think about how to find the maximum number of nested, can be set to a left parenthesis, right parenthesis is -1, it is clear that the largest amount of prefixes and seek. When the cursor is moved to modify the impact of it is the suffix, with the segment tree maintenance intervals can be.

#include<bits/stdc++.h>
using namespace std;
const int maxn=1e6+10;
int n,sum,now,a[maxn];
char s[maxn];
struct node{
	int l,r,maxx,minn,lazy;
}tree[maxn<<2];
void pushup(int x)
{
	tree[x].maxx=max(tree[x<<1].maxx,tree[x<<1|1].maxx);
	tree[x].minn=min(tree[x<<1].minn,tree[x<<1|1].minn);
}
void pushdown(int x)
{
	if(tree[x].lazy){
		tree[x<<1].maxx+=tree[x].lazy;
		tree[x<<1].minn+=tree[x].lazy;
		tree[x<<1].lazy+=tree[x].lazy;
		tree[x<<1|1].maxx+=tree[x].lazy;
		tree[x<<1|1].minn+=tree[x].lazy;
		tree[x<<1|1].lazy+=tree[x].lazy;
		tree[x].lazy=0;
	}
}
void build(int x,int l,int r)
{
	tree[x].l=l;tree[x].r=r;
	if(l==r) {
		tree[x].lazy=tree[x].maxx=tree[x].minn=0;
		return ;
	}
	int mid=(l+r)>>1;
	build(x<<1,l,mid);
	build(x<<1|1,mid+1,r);
	pushup(x);
}
void update(int x,int l,int r,int v)
{
	if(l<=tree[x].l&&tree[x].r<=r)
	{
		tree[x].maxx+=v;
		tree[x].minn+=v;
		tree[x].lazy+=v; 
		return ;
	}
	pushdown(x);
	int mid=(tree[x].l+tree[x].r)>>1;
	if(l<=mid) update(x<<1,l,r,v);
	if(mid<r) update(x<<1|1,l,r,v);
	pushup(x);
}
int main()
{
	scanf("%d",&n);
	scanf("%s",s+1);
	now=1;sum=0;
	build(1,1,n);
	for(int i=1;i<=n;++i){
		if(s[i]=='(')
		{
			if(a[now]==0) update(1,now,n,1),sum++;
			else if(a[now]==-1) update(1,now,n,2),sum+=2;
			a[now]=1;
		}
		else if(s[i]==')')
		{
			if(a[now]==1) update(1,now,n,-2),sum-=2;
			else if(a[now]==0) update(1,now,n,-1),sum--;
			a[now]=-1;
		}
		else if(s[i]=='L') {
			if(now>1) now--;
		}
		else if(s[i]=='R') now++;
		else {
			if(a[now]==1) update(1,now,n,-1),sum--;
			else if(a[now]==-1) update(1,now,n,1),sum++;
			a[now]=0;
		}
		if(sum==0&&tree[1].minn>=0) printf("%d",tree[1].maxx);
		else printf("-1");
		printf("%s",(i==n)?"\n":" ");
	}
 } 
Published 70 original articles · won praise 0 · Views 2371

Guess you like

Origin blog.csdn.net/qq_42479630/article/details/104255551