题目链接:点击进入
题目


题意
给 n 个匹配串,m 此询问,每次询问给出一个模式串,问模式串能匹配几个匹配串。
? 万能匹配符,也可以当作空白。
思路
将 n 个匹配串插入到字典树中,对于每次询问去字典树上搜索查找,对于 ?的部分,分别将其当作 ’ a ’ - ’ e ’ 以及 空白 来处理。
代码
// Problem: Bathroom terminal
// Contest: Virtual Judge - CodeForces
// URL: https://vjudge.net/problem/CodeForces-852G
// Memory Limit: 262 MB
// Time Limit: 2000 ms
//
// Powered by CP Editor (https://cpeditor.org)
//#pragma GCC optimize(3)//O3
//#pragma GCC optimize(2)//O2
#include<iostream>
#include<string>
#include<map>
#include<set>
//#include<unordered_map>
#include<queue>
#include<cstdio>
#include<vector>
#include<cstring>
#include<stack>
#include<algorithm>
#include<iomanip>
#include<cmath>
#include<fstream>
#define X first
#define Y second
#define base 233
#define INF 0x3f3f3f3f3f3f3f3f
#define pii pair<int,int>
#define lowbit(x) x & -x
#define inf 0x3f3f3f3f
//#define int long long
//#define double long double
//#define rep(i,x,y) for(register int i = x; i <= y;++i)
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const double pai=acos(-1.0);
const int maxn=5e6+10;
const int mod=1e9+7;
const double eps=1e-9;
const int N=5e3+10;
/*--------------------------------------------*/
inline int read()
{
int k = 0, f = 1 ;
char c = getchar() ;
while(!isdigit(c)){if(c == '-') f = -1 ;c = getchar() ;}
while(isdigit(c)) k = (k << 1) + (k << 3) + c - 48 ,c = getchar() ;
return k * f ;
}
/*--------------------------------------------*/
string s;
int n,m,len,tot;
int t[maxn][5],val[maxn];
bool vis[maxn];
void insert(string str)
{
int len=str.length(),p=0;
for(int i=0;i<len;i++)
{
int to=str[i]-'a';
if(t[p][to]==0)
t[p][to]=++tot;
p=t[p][to];
}
val[p]++;
}
int dfs(int p,int pos)
{
if(pos==len)
{
if(vis[p]) return 0;
else
{
vis[p]=1;
return val[p];
}
}
if(s[pos]>='a'&&s[pos]<='e')
{
int to=t[p][s[pos]-'a'];
if(to)
return dfs(to,pos+1);
else
return 0;
}
else
{
int ans=dfs(p,pos+1);
for(int i=0;i<5;i++)
{
if(t[p][i])
ans+=dfs(t[p][i],pos+1);
}
return ans;
}
}
int main()
{
// ios::sync_with_stdio(false);
// cin.tie(0);cout.tie(0);
cin>>n>>m;
for(int i=1;i<=n;i++)
{
cin>>s;
insert(s);
}
while(m--)
{
for(int i=0;i<=tot;i++) vis[i]=0;
cin>>s;
len=s.size();
cout<<dfs(0,0)<<endl;
}
return 0;
}

本文介绍了一种使用字典树解决给定n个匹配串的问题,通过搜索查找并处理问号字符的不同情况,快速求解每次模式串能匹配多少个匹配串。
422

被折叠的 条评论
为什么被折叠?



