题解:AT_abc403_e [ABC403E] Forbidden Prefix

· · 题解

赛时该切的题,因为 B 花了太久时间调然后这题又再往 hash 上面想没写完。

Trie 树板子题。

考虑权值 Trie 树。

考虑只有 2 操作时的维护方法:每一次操作时,在串的尾端打上一个标记,树的每一个节点统计子树上有多少个标记。

然后考虑 1 操作,要求 2 有 1 的前缀时子树答案清零,直接在字符串的末尾对应的节点打个标记就清零了。

每一次查询根节点的答案即可。

#include<bits/stdc++.h>
#define int long long
using namespace std;

const int N=1e6; 
struct node{
    int tag0,tag1;
    //tag0 表上代表清零其值,tag1 代表本子树的值 
    int son[35];
    int ans; 
}trie[N];
int idx=1;
string s;
int n;
void insert(int now,int now1,int op){
//  cout<<'^'<<endl;
//  cout<<now<<' '<<now1<<' '<<op<<' '<<sonidx<<endl;
    if(now1==n+1){
        trie[now].tag1++;
        if(op==1)   trie[now].tag0=1;
        trie[now].ans=trie[now].tag1;
        for(int i=1;i<=26;i++){
            trie[now].ans+=trie[trie[now].son[i]].ans;
        }
        if(trie[now].tag0)  trie[now].ans=0;
        return;
    }
    int sonidx=s[now1]-'a'+1;
    int nxt;
    if(trie[now].son[sonidx])   nxt=trie[now].son[sonidx];
    else    trie[now].son[sonidx]=++idx,nxt=idx;
//  cout<<now<<' '<<now1<<' '<<op<<' '<<sonidx<<' '<<op<<endl;
    insert(trie[now].son[sonidx],now1+1,op);
    trie[now].ans=trie[now].tag1;
    for(int i=1;i<=26;i++){
        trie[now].ans+=trie[trie[now].son[i]].ans;
    }
    if(trie[now].tag0)  trie[now].ans=0;
}
signed main(){
    int q;
    cin>>q;
    while(q--){
        int op;
        cin>>op;
        cin>>s;
        n=s.size();
        s=' '+s;
        insert(1,1,op);
        cout<<trie[1].ans<<endl;
    }
    cout<<endl;
    return 0;
} //ABC403E1