Description
- 有一个边为字符的树(字符集大小为 2 n 2n 2n)。
- q q q次在线操作。
- 修改:在某一个点下面加点。
- 询问:对于一个节点 x x x到它的根节点的路径上的字符串 S S S,已有一个它的长度为 l l l的前缀,每一次随机在后面加入字符集中的一个字符,问期望多少次能够得到 S S S。
- 对998244353取模。
- q , n ≤ 3 e 5 q,n\le3e5 q,n≤3e5
Solution
- 首先考虑一个串 S S S的时候怎么计算,与[CTSC2006]歌唱王国是一样的,考虑这个串的所有border,期望步数为:
∑ i = 1 ∣ S ∣ [ i i s b o r d e r ] ( 2 n ) i \sum_{i=1}^{|S|}[i\ is\ border](2n)^i i=1∑∣S∣[i is border](2n)i
- 这个可以通过概率生成函数推知。
- 或者可以设 f i f_i fi表示匹配了 i i i这个前缀之后的期望步数,注意到 f i f_i fi的转移只与 0 0 0到 i + 1 i+1 i+1的 f f f有关,因此可以用 f 0 f_0 f0从小到大去表示 f i f_i fi直到 f n f_n fn,然后通过 f n = 0 f_n=0 fn=0解出 f 0 f_0 f0即可。
- 然后只需要快速对于树上每一个节点寻找next即可。
- 暴力跳border可以被卡成 O ( n ) O(n) O(n),考虑如果当前 b o r d e r > l e n 2 border>\frac{len}{2} border>2len,那么所有长度大于 l e n 2 \frac{len}{2} 2len的border是一个公差为 l e n − b o r d e r len-border len−border的等差数列。
- 因此只需要跳 l o g log log次即可,每一次缩减为之前的 2 / 3 2/3 2/3。
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#define maxn 600005
#define maxp 20
#define ll long long
#define mo 998244353
using namespace std;
int id,c,L,q,n,i,j,k,tp;
int fa[maxn][maxp],dep[maxn],col[maxn],nxt[maxn],nxc[maxn],nx0[maxn];
ll mul[maxn],s[maxn];
void read(int &x){
x=0; char ch=getchar();
for(;ch<'0'||ch>'9';ch=getchar());
for(;ch>='0'&&ch<='9';ch=getchar()) x=x*10+ch-'0';
}
int jump(int x,int d){
for(int i=maxp-1;i>=0;i--) if (d>>i&1)
x=fa[x][i];
return x;
}
void add(int f,int v){
int x=++n; col[x]=v,fa[x][0]=f,dep[x]=dep[f]+1;
for(int i=1;i<maxp;i++) fa[x][i]=fa[fa[x][i-1]][i-1];
int y=f;
while (y!=1){
if (nxc[y]==col[x]){
nxt[x]=jump(x,dep[x]-dep[nxt[y]]-1);
nxc[x]=col[jump(x,dep[x]-dep[nxt[x]]-1)];
break;
} else y=nx0[y];
}
if (y==1) {
nxt[x]=1;
nxc[x]=col[jump(x,dep[x]-1)];
}
y=nxt[x];
if (dep[y]*2>=dep[x]) {
int k=dep[x]-dep[y];
int d=dep[x]-dep[x]/2/k*k;
nx0[x]=jump(x,dep[x]-d);
} else
nx0[x]=nxt[x];
s[x]=(s[nxt[x]]+mul[dep[x]])%mo;
}
int main(){
freopen("ceshi.in","r",stdin);
freopen("ceshi.out","w",stdout);
// freopen("rna.in","r",stdin);
// freopen("rna.out","w",stdout);
read(id),read(c),read(L),read(q),read(tp),n=1;
mul[0]=1;for(i=1;i<=L+q;i++) mul[i]=mul[i-1]*(2*c)%mo;
for(i=1;i<=L;i++) read(k),add(n,k);
int ans=0;
int cnt=0;
while (q--){
char ch=getchar(); while (ch!='A'&&ch!='Q') ch=getchar();
if (ch=='A'){
int x,v; read(x),read(v),v=(v+ans*tp)%(2*c);
add(x+L+1,v);
} else {
int x,y;
read(x),read(y);
x=x+L+1,y=(y+ans*tp)%(dep[x]+1);
y=jump(x,dep[x]-y);
ans=(s[x]-s[y]+mo+mo)%mo;
printf("%d\n",ans);
}
}
}