洛谷 P2292 L语言 trie树+暴力
题目大意:给你n个短串,然后再给你m个长串,让你对每一个长串求能被短串组成的最长长度
这题其实是一个简单思维题,然后暴力即可
首先,我们看题,给我们n个字符串,然后,建立trie树。
然后我们对每一个长串进行遍历,遍历的时候,我们对每一个短串能到达的结尾位置进行标记,然后每碰到这样一个标记,就往trie树上遍历查找,一直找到新的单词结尾,然后标记。
就这样一直找下去,因为短串长度只有那么多,所以时间复杂度是能过的,找到最后就是最长的地方,这个做法有点像bfs,但又有点区别。
上代码
#include <bits/stdc++.h>
using namespace std;
#define ll long long
const int maxn=1e6+7;;
int n,m,trie[maxn][26],tot=0,fail[maxn],num[maxn];
char str[maxn];
void build(char stt[]){
int len=strlen(stt),root=0;
for(int i=0;i<len;i++){
int id=stt[i]-'a';
if(!trie[root][id])
trie[root][id]=++tot;
root=trie[root][id];
}
num[root]++;
}
int getans(char stt[]){
int len=strlen(stt+1),root=0,ans=0,dp[maxn];
fill(dp,dp+1+len,0);
dp[0]=1;
for(int i=0;i<=len;i++){
if(!dp[i] && i)
continue;
root=0;
for(int j=i+1;j<=len;j++){
int id=stt[j]-'a';
if(!trie[root][id])
break;
root=trie[root][id];
if(num[root])
ans=max(ans,j),dp[j]=1;
}
}
return ans;
}
int main(){
memset(num,0,sizeof(num));
scanf("%d %d",&n,&m);
for(int i=1;i<=n;i++){
scanf("%s",str);
build(str);
}
for(int i=1;i<=m;i++){
scanf("%s",str+1);
printf("%d\n",getans(str));
}
return 0;
}