一眼 ddp,但不会 dp 方程。
Solution
考虑没有修改怎么做。考虑 dp:
设 表示前 个字符,结尾为 的不同非空子序列个数,则前 个字符总共的不同非空子序列个数为 。
记 为给定的字符串,可以发现:
- 初值:。
- 若 ,则 。
- 若 ,则 。
- 若 ,则 。
接下来是对 dp 合法性的说明:
设当前考虑的是 :
若 不可以变成 ,则 对 没有贡献,故此时 ;
若 可以变成 ,则我们可以通过以下方法构造出前 个字符,以 结尾的所有不同非空子序列:
- 将前 个字符构成的所有不同非空子序列的结尾接上 。
- 单独提出 。
前一种方法的方案数是 ,后一种则是 。于是我们得到此时 。
可能会有读者疑问为什么这种构造方法是正确的,即做到不重不漏。下面是证明:
- 不重
由定义可得前 个字符构成的所有不同非空子序列不重,则接上 后仍然不重;
同时由于该构造方案无法构造出单独一个的 ,单独提出 后仍然不重。
- 不漏
由于上述构造方法没有考虑 不选的情况,故在此处讨论这种情况。
显然若不选 ,满足条件的子序列集合即为前 个字符,结尾为 的不同非空子序列集合。
将集合中每个子序列结尾的 替换为 对应的 ,我们得到了 必选的情况。
所以不选的情况对答案没有贡献。由此得到上述构造方案不漏。
接下来考虑加上单点修改怎么做。
沿用 ddp 的套路,我们将转移方程写成矩阵相乘的形式。
- 若 ,则:
- 若 ,则:
- 若 ,则:
线段树维护矩阵乘积即可。注意维护的是翻转后的矩阵乘积。
实际上不翻转也没事,因为原字符串翻转前和翻转后的子序列是一一对应的。
Code
#include<bits/stdc++.h>
#define Tp template<typename T>
#define Ts template<typename T,typename... _T>
using namespace std;
using ll=long long;
char buf[1<<20],*p1=buf,*p2=buf;
#define getchar() (p1==p2&&(p2=buf+fread(p1=buf,1,1<<20,stdin),p1==p2)?EOF:*p1++)
Tp inline void read(T& x){
x=0;char c=getchar();bool f=0;
for(;c<48||c>57;c=getchar())c=='-'&&(f=1);
for(;c>47&&c<58;c=getchar())x=x*10+(c^48);
f&&(x=-x);
}
Ts inline void read(T& x,_T&... y){read(x),read(y...);}
Tp inline void assign(T *a,int n,T b){while(n--)*a++=b;}
Tp inline void copy(T *a,T *b,int n){while(n--)*a++=*b++;}
Tp inline void ckmin(T &a,T b){b<a&&(a=b);}
Tp inline void ckmax(T &a,T b){a<b&&(a=b);}
const int N=1e5+5,mod=998244353;
int n,q;char s[N];
struct Mat{
int a[3][3];
Mat(){memset(a,0,sizeof a);}
Mat(int a00,int a01,int a02,int a10,int a11,int a12,int a20,int a21,int a22){
a[0][0]=a00,a[0][1]=a01,a[0][2]=a02;
a[1][0]=a10,a[1][1]=a11,a[1][2]=a12;
a[2][0]=a20,a[2][1]=a21,a[2][2]=a22;
}
void clear(){memset(a,0,sizeof a);}
int* operator [](int i){return a[i];}
friend Mat operator *(Mat A,Mat B){
Mat C;C.clear();
for(int i=0;i<3;i++)
for(int k=0;k<3;k++)
for(int j=0;j<3;j++)
C[i][j]=(C[i][j]+(ll)A[i][k]*B[k][j])%mod;
return C;
}
};
Mat Init=Mat(0,0,0,0,0,0,1,0,0);
Mat Base[3]={
Mat(1,1,1,0,1,0,0,0,1),
Mat(1,0,0,1,1,1,0,0,1),
Mat(1,1,1,1,1,1,0,0,1)
};
int turn(char c){return c=='?'?2:c^48;}
#define lc (p<<1)
#define rc (p<<1|1)
int L[N<<2],R[N<<2],M[N<<2];
Mat T[N<<2];
void pushup(int p){T[p]=T[rc]*T[lc];}//T[p]=T[lc]*T[rc] 也可以
void build(int l,int r,int p=1){
L[p]=l,R[p]=r,M[p]=(l+r)>>1;
if(l==r){T[p]=Base[turn(s[l])];return;}
build(L[p],M[p],lc);
build(M[p]+1,R[p],rc);
pushup(p);
}
void update(int x,int p=1){
if(L[p]==R[p]){T[p]=Base[turn(s[x])];return;}
if(x<=M[p])update(x,lc);
else update(x,rc);
pushup(p);
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0),cout.tie(0);
cin>>n>>q>>(s+1);
build(1,n);
int x;char c;Mat res;
for(int i=1;i<=q;i++){
cin>>x>>c;
s[x]=c;update(x);
res=T[1]*Init;
cout<<(res[0][0]+res[1][0])%mod<<'\n';
}
return 0;
}