ABC473F 线段树
背景
不想说了,背景看这里,都怪雷霆 D。
我认为赛时做 D,还不如做 F,不仅分高,用时可能还短一点。
正文
::::info[分析]
我们来想怎么样的字符串
注意到只能添加 AB 和 A 两种字符串。把它们随意叠加有啥特点吗?
不难发现,只用这两种字符串,A 在每个位置数量的前缀和都会比 B 在该位置前缀和大。 |
|---|
| ::::info[证明] |
如何证明呢?我们可以维护 A 字符数量的前缀和 B 字符数量的前缀和 |
很明显,如果添加字符串 AB,先会让 A,则会直接变大。
所以字符串
那只要符合这个条件的字符串都是可以被构造的吗?
答案依然肯定。
每次我们遇到 B 都把它和离它最近的 A 匹配。
比如 AABB 这个字符串可以通过 AB 在正中间再添加 AB 得到。 |
|---|
| ::::info[优化] |
| 线段树优化。 |
操作一,在
- 如果没变,那不做操作。
- 如果改成
A,从这个字符一直到末尾+2 。 - 如果改成
B,从这个字符一直到末尾-2 。
为啥都是
操作二,判断
| 应用前面说的,可以维护这一段的最小值,然后减去 |
|---|
| ::::success[AC Code] |
| ```cpp |
| #include<iostream> |
| #define LL long long |
| #define F(i,k,n) for(int i=(k);i<=(n);++i) |
| #define RF(i,k,n) for(int i=(k);i>=(n);--i) |
| #define ls (p<<1) |
| #define rs (p<<1) |
| using namespace std; |
| struct node{ |
| int l; |
| int r; |
| int minn; |
| int lazy; |
| }tr[2000005]; |
| void build(int l,int r,int p=1){ |
| tr[p].l=l; |
| tr[p].r=r; |
| if(l==r){ |
| return; |
| } |
| int mid=l+r>>1; |
| build(l,mid,ls); |
| build(mid+1,r,rs); |
| return; |
| } |
| void push_up(int p){ |
| tr[p].minn=min(tr[ls].minn,tr[rs].minn); |
| return; |
| } |
| void push_down(int p){ |
| tr[ls].lazy+=tr[p].lazy; |
| tr[rs].lazy+=tr[p].lazy; |
| tr[ls].minn+=tr[p].lazy; |
| tr[rs].minn+=tr[p].lazy; |
| tr[p].lazy=0; |
| return; |
| } |
| void update(int l,int r,int y,int p=1){ |
| if(l<=tr[p].l&&tr[p].r<=r){ |
| tr[p].minn+=y; |
| tr[p].lazy+=y; |
| return; |
| } |
| push_down(p); |
| if(l<=tr[ls].r){ |
| update(l,r,y,ls); |
| } |
| if(tr[rs].l<=r){ |
| update(l,r,y,rs); |
| } |
| push_up(p); |
| return; |
| } |
| int query(int l,int r,int p=1){ |
| if(l<=tr[p].l&&tr[p].r<=r){ |
| return tr[p].minn; |
| } |
| push_down(p); |
| int minn=1e9; |
| if(l<=tr[ls].r){ |
| minn=min(minn,query(l,r,ls)); |
| } |
| if(tr[rs].l<=r){ |
| minn=min(minn,query(l,r,rs)); |
| } |
| push_up(p); |
| return minn; |
| } |
signed main(){ ios::sync_withstdio(0),cin.tie(0),cout.tie(0); int n; cin>>n; build(0,n); string s; cin>>s; s=' '+s; F(i,1,n){ if(s[i]=='A'){ update(i,n,1); }else{ update(i,n,-1); } } int ; cin>>; while(--){ int op; cin>>op; if(op==1){ int p; char c; cin>>p>>c; if(c==s[p]) continue; s[p]=c; if(s[p]=='A'){ update(p,n,2); }else{ update(p,n,-2); } }else{ int l,r; cin>>l>>r; if(query(l,r)-query(l-1,l-1)>=0){ cout<<"Yes\n"; }else{ cout<<"No\n"; } } } return 0; }
[评测记录](https://atcoder.jp/contests/abc473/submissions/78834430)。
::::
::::warning[提示]
- 线段树 4 倍空间。
::::
## 附记 ##
预期难度:上位绿