[HNOI 2004]L语言

Description

标点符号的出现晚于文字的出现,所以以前的语言都是没有标点的。现在你要处理的就是一段没有标点的文章。 一段文章T是由若干小写字母构成。一个单词W也是由若干小写字母构成。一个字典D是若干个单词的集合。 我们称一段文章T在某个字典D下是可以被理解的,是指如果文章T可以被分成若*分,且每一个部分都是字典D中的单词。 例如字典D中包括单词{‘is’, ‘name’, ‘what’, ‘your’},则文章‘whatisyourname’是在字典D下可以被理解的 因为它可以分成4个单词:‘what’, ‘is’, ‘your’, ‘name’,且每个单词都属于字典D,而文章‘whatisyouname’ 在字典D下不能被理解,但可以在字典D’=D+{‘you’}下被理解。这段文章的一个前缀‘whatis’,也可以在字典D下被理解 而且是在字典D下能够被理解的最长的前缀。 给定一个字典D,你的程序需要判断若干段文章在字典D下是否能够被理解。 并给出其在字典D下能够被理解的最长前缀的位置。

Input

输入文件第一行是两个正整数n和m,表示字典D中有n个单词,且有m段文章需要被处理。 之后的n行每行描述一个单词,再之后的m行每行描述一段文章。 其中1<=n, m<=20,每个单词长度不超过10,每段文章长度不超过1M。

Output

对于输入的每一段文章,你需要输出这段文章在字典D可以被理解的最长前缀的位置。

Sample Input

4 3
is
name
what
your
whatisyourname
whatisyouname
whaisyourname

Sample Output

14
6

HINT

整段文章’whatisyourname’都能被理解
前缀’whatis’能够被理解
没有任何前缀能够被理解

题解

我们将所有的单词翻转存入$Trie$中。

定义$bool$状态$f[i]$,表示$ch[1..i]$能否$(1/0)$被理解(字符串下标从$1$开始)。对于每次循环到的$i$,我们可以从$i$向前找到是否有单词匹配,若匹配,我们将$f[i] |= f[i-len]$,$len$为单词长度。

若$f[i]$为真,则可更新答案。

(由于单词的总字符长度不大,完全没必要用$AC$自动机。)

 //It is made by Awson on 2017.10.18
#include <set>
#include <map>
#include <cmath>
#include <ctime>
#include <stack>
#include <queue>
#include <vector>
#include <string>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
#define LL long long
#define Min(a, b) ((a) < (b) ? (a) : (b))
#define Max(a, b) ((a) > (b) ? (a) : (b))
#define Abs(x) ((x) < 0 ? (-(x)) : (x))
using namespace std;
const int LEN = ;
const int N = 1e6; int n, m, len;
char ch[N+];
bool f[N+]; struct TRIE {
int trie[LEN+][], pos;
bool val[LEN+];
void insert(char *ch) {
int u = , len = strlen(ch);
for (int i = len-; i >= ; i--) {
if (!trie[u][ch[i]-'a']) trie[u][ch[i]-'a'] = ++pos;
u = trie[u][ch[i]-'a'];
}
val[u] = ;
}
void query(int len, bool &x) {
int u = ;
for (int i = len; i >= ; i--) {
if (trie[u][ch[i]-'a']) u = trie[u][ch[i]-'a'];
else return;
if (val[u]) x |= f[i-];
}
}
}T; void work() {
scanf("%d%d", &n, &m);
for (int i = ; i <= n; i++) {
scanf("%s", ch), T.insert(ch);
}
while (m--) {
memset(f, , sizeof(f)); f[] = ;
scanf("%s", ch+); len = strlen(ch+); int ans = ;
for (int i = ; i <= len; i++) {
T.query(i, f[i]); if (f[i]) ans = i;
}
printf("%d\n", ans);
}
}
int main() {
work();
return ;
}
上一篇:js 实现json数组集合去重,差集,并集,交集。


下一篇:BZOJ 3439 Kpm的MC密码 (Trie树+线段树合并)