题解:P6727 [COCI 2015/2016 #5] OOP

· · 题解

给出一个由 n 个只有小写字母的字符串 S_i 构成的序列。

令 T=A*B,其中 * 为通配符。

我们就是要找到有多少 S_i 的前缀为 A,后缀为 B,长度 \ge \lvert T\rvert-1。

需要前后缀都出现,于是对于正反串建立 Trie,前后缀要求就转化为子树 dfs 序范围,然后又要求长度,于是就是三维偏序了。时间复杂度 O(n\log^2n)。

还有一个解法,我们对于前缀走 Trie,假设走到了节点 u,对于 u 的子节点寻找有无后缀哈希值在子节点中出现。这个直接离线 dfn 序扫描线,由于满足可减性可以不用线段树,直接 [l,r]=[1,r]-[1,l-1] 就行了。用 std::map 保存一下哈希值就可以做到 O(n\log n) 了。这个算法能省去一个 \log 的原因是第一个算法只在尾节点处产生贡献,而这个是在串的每个位置都产生一个后缀信息的贡献,这样子就省去对于长度的约束了。

#include<bits/stdc++.h>
#define pb emplace_back
#define fi first
#define se second
#define mp make_pair
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int maxn=3e6+10;
const int maxm=3e6+10;
void chkmax(int &x,int y){ x=x>y?x:y; }
void chkmin(int &x,int y){ x=x<y?x:y; }
struct Que{
    int id,v; ull hh;
}; vector<Que> Q[maxm];
vector<ull> vec[maxn];
int ans[maxn]; map<int,int> S;
struct Hash{
    ull h[maxn],p[maxn];
    void init(char *s,int n){
        p[0]=1; for(int i=1;i<=n;i++) p[i]=p[i-1]*1337;
        for(int i=1;i<=n;i++) 
            if(s[i]!='*') h[i]=h[i-1]*1337+(s[i]-'a'+1);
            else h[i]=h[i-1]*1337;
    }
    ull get(int l,int r){ if(l>r) return 0; return h[r]-h[l-1]*p[r-l+1]; }
}h;
int id(char c){ return c-'a'+1; }
struct Trie{
    int dfn[maxn],ch[maxn][27],sz[maxn],Id[maxn],tot,cnt;
    void init(){ tot=1; cnt=0; }
    void ins(char *s){
        int u=1,m=strlen(s+1);
        for(int i=1;i<=m;i++){
            int x=id(s[i]); vec[u].pb(h.get(i,m));
            if(!ch[u][x]) ch[u][x]=++tot;
            u=ch[u][x];
        }
        vec[u].pb(0);
    }
    int dfs(int u){
        dfn[u]=++cnt; Id[cnt]=u; sz[u]=1;
        for(int i=1;i<=26;i++)
            if(ch[u][i]) sz[u]+=dfs(ch[u][i]);
        return sz[u];
    }
    void find(char *s,int m,ull M,int Id){
        int u=1;
        for(int i=1;i<=m;i++) u=ch[u][id(s[i])];
        if(!u) return ;
        Q[dfn[u]-1].pb((Que){Id,-1,M});
        Q[dfn[u]+sz[u]-1].pb((Que){Id,1,M});
    }
}t; char s[maxn]; int n,q;
int main(){
    ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
    cin>>n>>q; t.init();
    for(int i=1;i<=n;i++){
        cin>>(s+1); h.init(s,strlen(s+1));
        t.ins(s);
    }
    t.dfs(1);
    for(int i=1;i<=q;i++){
        cin>>(s+1); int m=strlen(s+1);
        h.init(s,m); int pos;
        for(int j=1;j<=m;j++)
            if(s[j]=='*') pos=j;
        t.find(s,pos-1,h.get(pos+1,m),i);
    }
    for(int i=1;i<=t.tot;i++){
        for(auto z:vec[t.Id[i]]) S[z]++;
        for(auto z:Q[i]) 
            if(S.find(z.hh)!=S.end()) ans[z.id]+=z.v*S[z.hh];
    }
    for(int i=1;i<=q;i++) cout<<ans[i]<<"\n";
    return 0;
}