题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1251
题意:给出一些单词,统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀)。
思路:建trie树,记录每个字母的经过次数。
如果以某个字符串为前缀,我们在树上按照这个字符串走到最后一个字母的位置,答案就是最后一个字母的经过次数。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
using namespace std;
#define rep(i,j,k) for(int i = j; i <= k; i++ )
#define Rrep(i,j,k) for(int i = j; i >= k; i-- )
#define Clean(x,y) memset(x,y,sizeof(x))
const int maxn = 26;
struct trie
{
trie* next[maxn];
int num;
};
void init(trie *x)
{
x->num = 0;
rep(i,0,maxn-1) x->next[i] = NULL;
}
void insert(trie* x , char s[])
{
int k = 0;
while( s[k] )
{
int index = s[k] - 'a';
if ( x->next[index] == NULL )
{
x->next[index] = new trie;
init(x->next[index]);
}
x = x->next[index];
x->num++;
k++;
}
}
int query(trie* x,char s[])
{
int k = 0;
while( s[k] )
{
int index = s[k] - 'a';
if ( x->next[index] == NULL ) return 0;
x = x->next[index];
k++;
}
return x->num;
}
char temp[209];
char c;
trie* T;
int main()
{
T = new trie;
init(T);
while( ( c = getchar() ) != '\n' )
{
int len = 0;
temp[0] = c;
while( ( c = getchar() ) != '\n' ) temp[++len] = c;
temp[++len] = '\0';
insert(T,temp);
}
while(gets(temp))
{
printf("%d\n",query(T,temp));
}
return 0;
}