蒟蒻求助,跟着第二篇题解思路改的 ,样例输出全是负数
查看原帖
蒟蒻求助,跟着第二篇题解思路改的 ,样例输出全是负数
574890
zfy2006楼主2022/6/2 15:35
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N=1e5+5;
char s[N],s2[N];
string ss[N];
int n,m,cnt,tot,sum,num;
struct o{
    int fail,num;
    int ch[30];
}t[N];
int mp[N],c[N],trie[N][26],head[N],h1[N],tot2,tot1,sz[N],id[N],ans[N],ql[N],qr[N];
struct ooo{
    int ne,to;
}e[N<<1];
struct oo{
    int x,y,id;
}q1[N];
inline bool cmp(oo a,oo b){
    return a.y<b.y;
}
inline void add(int x,int y){
    e[++tot1].ne=head[x];
    head[x]=tot1;
    e[tot1].to=y;
}
inline void ad(int x,int k){
    for(;x<=cnt;x+=x&-x)c[x]+=k;
}
inline int ask(int x){
    int sn=0;
    for(;x;x-=x&-x) sn+=c[x];
    return sn;
}
inline void dfs1(int x,int fa){
    id[x]=++num;
    sz[x]=1;
    for(int i=head[x];i;i=e[i].ne){
        int to=e[i].to;
        if(to==fa)continue;
        dfs1(to,x);
        sz[x]+=sz[to];
    }
}
inline void dfs2(int x){
    ad(id[x],1);
    if(t[x].num){
        for(int i=ql[x];i<=qr[x];i++){
            int to=mp[q1[i].x];
            ans[q1[i].id]=ask(id[to]+sz[to]-1)-ask(id[to]-1);
        }
    }
    for(int i=0;i<26;i++){
        if(trie[x][i]){
            dfs2(trie[x][i]);
        }
    }
    ad(id[x],-1);
    return;
}
inline void build(int id){
    int x=0;
    for(int i=0;i<tot;i++){
        int to=s2[i]-'a';
        if(!t[x].ch[to])t[x].ch[to]=++cnt,trie[x][to]=cnt;
        x=t[x].ch[to];
    }
    if(!t[x].num)t[x].num=id;
    mp[id]=x;
}
queue<int>q;
inline void gf(){
    for(int i=0;i<26;i++){
        if(t[0].ch[i]){
            t[t[0].ch[i]].fail=0;
            q.push(t[0].ch[i]);
        }
    }
    while(!q.empty()){
        int x=q.front();
        q.pop();
        for(int i=0;i<26;i++){
            int to=t[x].ch[i];
            if(to){
                t[to].fail=t[t[x].fail].ch[i];
                q.push(to);
            }else t[x].ch[i]=t[t[x].fail].ch[i];
        }
    }
}
signed main(){
    ios::sync_with_stdio(false);
    cin.tie(0),cout.tie(0);
    cin>>s;
    n=strlen(s);
    for(int i=0;i<n;i++){
        if(s[i]=='P'){
            ss[++sum]=s2;
            build(sum);
        }else if(s[i]=='B')tot--,s2[tot]=0;
        else s2[tot++]=s[i];
    }
    gf();
    cin>>m;
    for(int i=1;i<=m;i++){
        cin>>q1[i].x>>q1[i].y;
        q1[i].y=mp[q1[i].y];
        q1[i].id=i;
    }
    sort(q1+1,q1+m+1,cmp);
    for(int i=1;i<=cnt;i++){
        add(t[i].fail,i);
    }
    dfs1(0,-1);
    for(int i=1,p=1;i<=m;i=p){
        ql[q1[i].y]=i;
        while(q1[p].y==q1[i].y)p++;
        qr[q1[i].y]=p-1;
    }
    dfs2(0);
    for(int i=1;i<=m;i++)cout<<ans[i]<<endl;
    return 0;
}
2022/6/2 15:35
加载中...