[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$自动机。)

 1 //It is made by Awson on 2017.10.18
 2 #include <set>
 3 #include <map>
 4 #include <cmath>
 5 #include <ctime>
 6 #include <stack>
 7 #include <queue>
 8 #include <vector>
 9 #include <string>
10 #include <cstdio>
11 #include <cstdlib>
12 #include <cstring>
13 #include <iostream>
14 #include <algorithm>
15 #define LL long long
16 #define Min(a, b) ((a) < (b) ? (a) : (b))
17 #define Max(a, b) ((a) > (b) ? (a) : (b))
18 #define Abs(x) ((x) < 0 ? (-(x)) : (x))
19 using namespace std;
20 const int LEN = 200;
21 const int N = 1e6;
22 
23 int n, m, len;
24 char ch[N+5];
25 bool f[N+5];
26 
27 struct TRIE {
28     int trie[LEN+5][26], pos;
29     bool val[LEN+5];
30     void insert(char *ch) {
31         int u = 0, len = strlen(ch);
32         for (int i = len-1; i >= 0; i--) {
33             if (!trie[u][ch[i]-'a']) trie[u][ch[i]-'a'] = ++pos;
34             u = trie[u][ch[i]-'a'];
35         }
36         val[u] = 1;
37     }
38     void query(int len, bool &x) {
39         int u = 0;
40         for (int i = len; i >= 1; i--) {
41             if (trie[u][ch[i]-'a']) u = trie[u][ch[i]-'a'];
42             else return;
43             if (val[u]) x |= f[i-1];
44         }
45     }
46 }T;
47 
48 void work() {
49     scanf("%d%d", &n, &m);
50     for (int i = 1; i <= n; i++) {
51         scanf("%s", ch), T.insert(ch);
52     }
53     while (m--) {
54         memset(f, 0, sizeof(f)); f[0] = 1;
55         scanf("%s", ch+1); len = strlen(ch+1); int ans = 0;
56         for (int i = 1; i <= len; i++) {
57             T.query(i, f[i]); if (f[i]) ans = i;
58         }
59         printf("%d\n", ans);
60     }
61 }
62 int main() {
63     work();
64     return 0;
65 }

 

posted @ 2017-10-18 21:30  NaVi_Awson  阅读(235)  评论(0编辑  收藏  举报