题解:P6727 [COCI 2015/2016 #5] OOP
给出一个由
n 个只有小写字母的字符串S_i 构成的序列。
令
我们就是要找到有多少
需要前后缀都出现,于是对于正反串建立 Trie,前后缀要求就转化为子树 dfs 序范围,然后又要求长度,于是就是三维偏序了。时间复杂度
还有一个解法,我们对于前缀走 Trie,假设走到了节点 std::map 保存一下哈希值就可以做到
#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;
}