题意:Ignatius最近遇到一个难题,老师交给他很多单词(只有小写字母组成,不会有重复的单词出现),现在老师要他统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀).
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1251
——>>叫统计难题,其实是。。。。。。
只需组织好Trip,并保存每个结点被单词经过的次数。。。询问时沿着Trip走就是。。。
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
const int maxw = 10 + 5;
char name[maxw], pre[maxw];
struct node{
int cnt;
node *next[26];
node(){
cnt = 0;
memset(next, 0, sizeof(next));
}
};
struct Trip{
node *root;
Trip(){
root = new node;
}
int idx(char c){
return c - 'a';
}
void insert(char *s){
int len = strlen(s), i;
node *t = root;
for(i = 0; i < len; i++){
int c = idx(s[i]);
if(!t->next[c]) t->next[c] = new node;
t->next[c]->cnt++;
t = t->next[c];
}
}
void solve(char *s){
int ret = -1;
node *t = root;
int len = strlen(s);
for(int i = 0; i < len; i++){
int c = idx(s[i]);
t = t->next[c];
if(!t){
ret = 0;
break;
}
}
if(ret == -1) ret = t->cnt;
printf("%d\n", ret);
}
};
int main()
{
Trip trip;
while(gets(name)){
if(!strlen(name)) break;
trip.insert(name);
}
while(scanf("%s", pre) == 1){
trip.solve(pre);
}
return 0;
}