banana band bee absolute acm ba b band abc
2 3 1 0
解题分析:
这里的意义就是查找前缀
可以用字典树来写,TrieTree
这里还需要处理的就是对于输入的问题:
while(scanf("%s", str) && str[0])
{
}
代码:
#include <iostream>
#include <cstdio>
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;
}