题目分析:
画一下fail树,就会发现就是x的子树中属于y路径的,把y剖分一下,用线段树处理
$O(n*log^2 n)$。
代码:
#include<bits/stdc++.h>
using namespace std; const int maxn = ; string str;
struct node{int ch[],fail,fa;}T[maxn];
int star[maxn],ans[maxn],num = ,snum,m;
int dfsin[maxn],dfsout[maxn],poss[maxn]; // failtree
int Tnb[maxn],top[maxn],sz[maxn];
vector <int> g[maxn];
vector<pair<int,int> > Qy[maxn]; void read(){
ios::sync_with_stdio(false);
cin.tie();
cin >> str;
int now = ;
for(int i=;i<str.length();i++){
if(str[i] == 'B') now = T[now].fa;
else if(str[i] == 'P') star[++snum] = now;
else{
if(T[now].ch[str[i]-'a']) now = T[now].ch[str[i]-'a'];
else{
T[now].ch[str[i]-'a'] = ++num;
T[num].fa = now;
now = num;
}
}
}
snum = ;
} void dfs(int now){
dfsin[now] = dfsout[now] = ++snum;
poss[snum] = now;
for(int i=;i<g[now].size();i++){
dfs(g[now][i]);
dfsout[now] = dfsout[g[now][i]];
}
} queue<int> q;
void BuildACAutomaton(){
q.push();T[].fail = ;
while(!q.empty()){
int k = q.front();q.pop();
for(int i=;i<;i++){
if(T[k].ch[i] == ) continue;
int ff = T[k].fail;
while(ff != && T[ff].ch[i] == ) ff = T[ff].fail;
if(T[ff].ch[i]==T[k].ch[i]||T[ff].ch[i]==)T[T[k].ch[i]].fail=;
else T[T[k].ch[i]].fail = T[ff].ch[i];
q.push(T[k].ch[i]);
g[T[T[k].ch[i]].fail].push_back(T[k].ch[i]);
}
}
snum = ; dfs(); snum = ;
} int QT[maxn*]; void Add(int now,int tl,int tr,int pos){
if(tl == tr){QT[now]++;return;}
int mid = (tl+tr)/;QT[now]++;
if(mid >= pos) Add(now<<,tl,mid,pos);
else Add(now<<|,mid+,tr,pos);
}
int Query(int now,int tl,int tr,int l,int r){
if(tl >= l && tr <= r) return QT[now];
if(tl > r || tr < l) return ;
int mid = (tl+tr)/;
return Query(now<<,tl,mid,l,r)+Query(now<<|,mid+,tr,l,r);
} void dfsmiao(int now){
for(int i=;i<;i++){
if(T[now].ch[i]==)continue;
dfsmiao(T[now].ch[i]);
sz[now] += sz[T[now].ch[i]];
}
sz[now]++;
} void dfsyeah(int now,int tp){
int son = ;top[now] = tp;Tnb[now] = ++snum;
for(int i=;i<;i++){
if(sz[T[now].ch[i]] > sz[son]) son = T[now].ch[i];
}
if(son) dfsyeah(son,tp);
for(int i=;i<;i++){
if(T[now].ch[i] == || T[now].ch[i] == son) continue;
dfsyeah(T[now].ch[i],T[now].ch[i]);
}
} void treechain(){
dfsmiao();
dfsyeah(,);
} void readquery(){
cin >> m;
for(int i=;i<=m;i++){
int x,y; cin >> x >> y;
x = star[x];y = star[y];
Qy[poss[dfsin[x]-]].push_back(make_pair(y,i));
Qy[poss[dfsout[x]]].push_back(make_pair(y,i));
}
} void solve(int endpos,int now){
if(ans[now]) ans[now] = -ans[now];
while(endpos){
ans[now] += Query(,,num,Tnb[top[endpos]],Tnb[endpos]);
endpos = T[top[endpos]].fa;
}
} void work(){
for(int i=;i<=num;i++){
int now = poss[i];
Add(,,num,Tnb[now]);
for(int j=;j<Qy[now].size();j++){
solve(Qy[now][j].first,Qy[now][j].second);
}
}
for(int i=;i<=m;i++) cout<<ans[i]<<endl;
} int main(){
//freopen("7.in","r",stdin);
read();
treechain();
BuildACAutomaton();
readquery();
work();
return ;
}