给N个模式串,每个不超过个字符,再给M个句子,句子长度< 100 判断每个句子里是否包含模式串 N < 10, M < 10 ,字符都是小写字母
5 8
abcde
defg
cdke
ab
f
abcdkef
abkef
bcd
bca
add
ab
qab
f
题解:本题为trie图模板题,直接套基础模板就好了,这道题的函数可以当作模板用。
#include <iostream>
#include <cstdio>
#include <string>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <vector>
#include <map>
#include <set>
#include <queue>
using namespace std;
const int maxn = 105;
const int LETTERS = 26;
int nNodesCount = 0;
struct CNode
{
CNode *pchilds[LETTERS];
CNode *pPrev;
bool bBadNode;
void Init()
{
memset (pchilds, 0, sizeof(pchilds));
bBadNode = false;
pPrev = NULL;
}
};
CNode Tree[200];
void Insert(CNode *pRoot, char *s)
{
for (int i = 0; s[i]; i++) {
if (pRoot->pchilds[s[i] - 'a'] == NULL) {
pRoot->pchilds[s[i] - 'a'] = Tree + nNodesCount;
nNodesCount++;
}
pRoot = pRoot->pchilds[s[i] - 'a'];
}
pRoot->bBadNode = true;
}
void BuildDfa()
{
for (int i = 0; i < LETTERS; i++) {
Tree[0].pchilds[i] = Tree + 1;
}
Tree[0].pPrev = NULL;
Tree[1].pPrev = Tree;
deque<CNode *> q;
q.push_back(Tree + 1);
while (!q.empty()) {
CNode *pRoot = q.front();
q.pop_front();
for (int i = 0; i < LETTERS; i++) {
CNode *p = pRoot->pchilds[i];
if (p) {
CNode *pPrev = pRoot->pPrev;
while (pPrev) {
if (pPrev->pchilds[i]) {
p->pPrev = pPrev->pchilds[i];
if (p->pPrev->bBadNode) p->bBadNode = true;
break;
} else {
pPrev = pPrev->pPrev;
}
q.push_back(p);
}
}
}
}
}
bool SearchDfa(char *s)
{
CNode *p = Tree + 1;
for (int i = 0; s[i]; i++) {
while (1) {
if (p->pchilds[s[i] - 'a']) {
p = p->pchilds[s[i] - 'a'];
if (p->bBadNode) return true;
break;
} else {
p = p->pPrev;
}
}
}
return false;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen ("in.txt", "r", stdin);
#endif // ONLINE_JUDGE
int n, m;
while (scanf ("%d%d", &n, &m) != EOF) {
if (n == 0 && m == 0) break;
nNodesCount = 2;
char s[maxn];
for (int i = 0; i < n; i++) {
scanf ("%s", s);
Insert(Tree + 1, s);
}
BuildDfa ();
for (int i = 0; i < m; i++) {
scanf ("%s", s);
cout << SearchDfa (s) << endl;
}
}
return 0;
}