题解:P17894 [ICPC 2026 Nanchang I] The Meaning of the World
:::info[?!豪豪!?] :::
零秒时间联想到 P6781 然后顺畅的就做完了。非常极限的拿下来一血。
感觉很思路很顺畅啊,想到一步下一步就直接会了。经典题吧,感觉括号序列就是一个单侧递归非常优美的运用啊!
加训 Ynoi 是对的!
考虑一个非常简单的做法。
对于每一个区间单独做栈匹配,显然的经典结论就是留下来的必然是一段右括号和一段左括号。
假设它们的下标是
考虑放到线段树上维护这个匹配的过程。
假设线段树的这个节点,没有匹配的右括号数量是
令它的左右儿子分别是
它们直接可以消掉
于是此节点的
令
则对于答案的更新有
于是我们需要尝试维护出这个
令
当
当
对于翻转操作,考虑直接交换叶子的
容易发现复杂度是
:::success[code]
namespace my{
const int N=2e5+5,inf=1000000000;template<typename T>pref T Min(T x,T y){return x<y?x:y;}template<typename T>pref T Max(T x,T y){return x>y?x:y;}template<typename T>pref T Abs(T x){return x<0?-x:x;}
struct node{
int len,sum,mn,fst,lst,ans;
}t[N<<2];
string s;
pref node leaf(int v){
int pos=(v<0);
return {1,v,Min(0,v),pos,pos,0};
}
#define ls(p) (p<<1)
#define rs(p) (p<<1|1)
pref int first(int p,int h){
int d=0;
while(t[p].len>1){
int c=ls(p);
if(t[c].mn<h)p=c;
else h-=t[c].sum,d+=t[c].len,p=c^1;
}
return d+1;
}
pref int last(int p,int h){
int d=0;
while(t[p].len>1){
int c=rs(p);
if(t[c].mn-t[c].sum<h)p=c;
else h+=t[c].sum,d+=t[c].len,p=c^1;
}
return d+1;
}
pref node merge(const node&a,const node&b,int p){
int x=a.mn,y=a.sum+b.mn;
node c;
c.len=a.len+b.len,c.sum=a.sum+b.sum;
c.mn=Min(x,y),c.fst=(x<=y)?(a.fst):(a.len+b.fst);
c.lst=(x<y)?(a.lst):(a.len+b.lst);
int left=a.len-a.fst,right=b.lst;
if(x<y)left=last(ls(p),b.mn)-1;
if(x>y)right=first(rs(p),x-a.sum)-1;
c.ans=Max(Max(a.ans,b.ans),left+right);
return c;
}
void build(int p,int l,int r){
if(l==r){
t[p]=leaf(s[l-1]=='('?1:-1);
return ;
}
int mid=(l+r)>>1;
build(ls(p),l,mid);
build(rs(p),mid+1,r);
t[p]=merge(t[ls(p)],t[rs(p)],p);
}
void change(int p,int l,int r,int pos){
if(l==r){
t[p]=leaf(-t[p].sum);
return ;
}
int mid=(l+r)>>1;
pos<=mid?change(ls(p),l,mid,pos):change(rs(p),mid+1,r,pos);
t[p]=merge(t[ls(p)],t[rs(p)],p);
}
node query(int p,int l,int r,int L,int R){
if(L<=l&&r<=R)return t[p];
int mid=(l+r)>>1;
if(R<=mid)return query(ls(p),l,mid,L,R);
if(L>mid)return query(rs(p),mid+1,r,L,R);
return merge(query(ls(p),l,mid,L,R),query(rs(p),mid+1,r,L,R),p);
}
int n,Q;
pref void SOLVE(){
cin>>n>>Q>>s;build(1,1,n);
while(Q--){
int op,l,r;
cin>>op>>l;
if(op==1)change(1,1,n,l);
else
cin>>r,cout<<query(1,1,n,l,r).ans<<'\n';
}
}
}
:::