bzoj 2434: [Noi2011]阿狸的打字机
/************************************************************** Problem: 2434 User: wangyucheng Language: C++ Result: Accepted Time:496 ms Memory:21968 kb ****************************************************************/ #include<iostream> #include<cstdio> #include<cstring> #include<algorithm> using namespace std; #define in(x) scanf("%d",&x) #define in2(x,y) scanf("%d%d",&x,&y) #define in3(x,y,z) scanf("%d%d%d",&x,&y,&z) #define F(i,x) for(int i=1;i<=x;i++) #define N 110000 int p[N][30]; int g[N],nn; char a[N]; int to[N]; int im[N],n,fa[N],tot,m; int s[N*2]; void make(){ int now=0; for(int i=0;i<n;i++){ if(a[i]=='B'){ now=fa[now]; continue; } if(a[i]=='P'){ im[now]=++nn; to[nn]=now; continue; } if(!p[now][a[i]-'a'])p[now][a[i]-'a']=++tot,fa[tot]=now; now=p[now][a[i]-'a']; } } int tt,e[N],ne[N],v[N]; int tt2,e2[N],ne2[N],v2[N],num[N]; void add(int x,int y){ ne[++tt]=e[x],e[x]=tt,v[tt]=y; } void add2(int x,int y,int z){ ne2[++tt2]=e2[x],e2[x]=tt2,num[tt2]=z,v2[tt2]=y; } int qu[N],he,bo; void bfs(){ int y,x; qu[he=bo=1]=0; while(he>=bo){ x=qu[bo++]; for(int i=0;i<26;i++)if(p[x][i]){ qu[++he]=p[x][i]; int z=g[x]; for(;z!=-1&&!p[z][i];z=g[z]); if(z==-1)g[qu[he]]=0; else g[qu[he]]=p[z][i]; } } } int b1[N],b2[N],len; void jia(int x,int y){ for(int i=x;i<=len;i+=(i&-i))s[i]+=y; } int ask(int x){ int ans=0; for(int i=x;i>0;i-=(i&-i))ans+=s[i]; return ans; } void dfs1(int x){ b1[x]=++len; for(int i=e[x];i;i=ne[i]){ dfs1(v[i]); } b2[x]=len; } int res[N]; void solv(){ int now=0,k; for(int i=0;i<n;i++){ if(a[i]=='B'){ jia(b1[now],-1); now=fa[now]; continue; } if(a[i]=='P'){ for(int j=e2[im[now]];j;j=ne2[j]){ k=to[v2[j]]; res[num[j]]=ask(b2[k])-ask(b1[k]-1); } continue; } now=p[now][a[i]-'a']; jia(b1[now],1); } } int main(){ scanf("%s",a); g[0]=-1; n=strlen(a); in(m); make(); bfs(); F(i,tot)add(g[i],i); F(i,m){ int x,y; in2(x,y); add2(y,x,i); } dfs1(0); solv(); F(i,m)printf("%d\n",res[i]); }