HDOJ 1251 统计难题(trie树入门)
题意:
对于每个提问,给出以该字符串为前缀的单词的数量.
思路:
字典树。
#include <iostream>
using namespace std;
struct node {
int w;
int child[26];
} trie[1000010];
int size = 0;
void Insert(char* word, int i, int rt)
{
if (!word[i])
return ;
int m = word[i] - 'a';
if (trie[rt].child[m])
{
trie[trie[rt].child[m]].w += 1;
Insert(word, i + 1, trie[rt].child[m]);
}
else
{
trie[rt].child[m] = ++size;
trie[trie[rt].child[m]].w += 1;
Insert(word, i + 1, size);
}
}
int Query(char* word, int i, int rt)
{
if (!word[i])
return trie[rt].w;
int m = word[i] - 'a';
if (trie[rt].child[m])
return Query(word, i + 1, trie[rt].child[m]);
else
return 0;
}
int main()
{
char word[12];
while (gets(word) && word[0])
Insert(word, 0, 0);
while (gets(word))
printf("%d\n", Query(word, 0, 0));
return 0;
}
-------------------------------------------------------
kedebug
Department of Computer Science and Engineering,
Shanghai Jiao Tong University
E-mail: kedebug0@gmail.com
GitHub: http://github.com/kedebug
-------------------------------------------------------