跳到正文

题解

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

Mirasycle约 5 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 5 分钟
题目
P6727

版本

  1. v1当前

给出一个由 nn 个只有小写字母的字符串 SiS_i 构成的序列。 mm 次询问,每次给出一个恰好带通配符的询问串 TT,求这个串能与多少串 SiS_i 匹配。通配符可以替换为空串或者某个串。∑len≤3×106,n≤105\sum len \le 3\times10^6,n\le 10^5。

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

我们就是要找到有多少 SiS_i 的前缀为 AA,后缀为 BB,长度 ≥∣T∣−1\ge \lvert T\rvert-1。

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

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

C++
#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;
}
原文