思路:因为字典树只能读取前缀有多少个相同的, 对于求子串可以将字符串分成
多个字串看成单独的字符串 进行建 字典树,但要注意这两个字符串 abab, ab
他们的字串都有 ab a 所以在建树时 判断是否同一个字符串 不同就加 1 ;
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
struct Trie
{
int num;
int tot;//记录梅个字串对应的原字符串的序号
Trie *next[26];
Trie()
{
num = tot = 0;
memset(next, 0, sizeof(next));
}
}root;
void createTrie(char *str, int x)
{
int len = strlen(str);
Trie *p = &root, *q;
for(int i = 0; i < len; i++)
{
int id = str[i] - 'a';
if(p->next[id] == NULL)
{
q = new Trie;
p->next[id] = q;
}
p = p->next[id];
if(p->tot != x) p->num++;
p->tot = x;
}
}
int findTrie(char *str)
{
int len = strlen(str);
Trie *p = &root;
for(int i = 0; i < len; i++)
{
int id = str[i] - 'a';
p = p->next[id];
if(p == NULL) return 0;
}
return p->num;
}
int main()
{
int n;
char str[26];
while(cin >> n)
{
for(int i = 1; i <= n; i++)
{
cin >> str;
int len = strlen(str);
for(int j = 0; j < len; j++) createTrie(str+j, i);
}
cin >> n;
for(int i = 0; i < n; i++)
{
cin >> str;
cout << findTrie(str) << endl;
}
}
return 0;
}
hdu 2846 经典字典树
最新推荐文章于 2017-09-14 22:10:11 发布