统计难题 【字典树模版】

来源:互联网 发布:java 接口有什么用 编辑:程序博客网 时间:2024/04/30 06:22

Problem Description
Ignatius最近遇到一个难题,老师交给他很多单词(只有小写字母组成,不会有重复的单词出现),现在老师要他统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀).

Input
输入数据的第一部分是一张单词表,每行一个单词,单词的长度不超过10,它们代表的是老师交给Ignatius统计的单词,一个空行代表单词表的结束.第二部分是一连串的提问,每行一个提问,每个提问都是一个字符串.

注意:本题只有一组测试数据,处理到文件结束.

Output
对于每个提问,给出以该字符串为前缀的单词的数量.

Sample Input
banana
band
bee
absolute
acm

ba
b
band
abc

Sample Output
2
3
1
0

学习了,简单的字典树模板应用
代码

#include <iostream>#include<algorithm>#include<string.h>#include<stdio.h>#include<math.h>#include<stack>#define LL long longusing namespace std;const int MAXN= 1000000+10;const int inf =0x3f3f3f3f;/*--------------------------*/char str[100];char ask[100];int ch[MAXN][40];int word[MAXN];//记录该节点下的单词数目int val[MAXN];int sz; //标记单词的节点void init(){// 字典树     sz=1;    memset(ch[0],0,sizeof(ch[0]));    memset(word,0,sizeof(word));}int idx(char x){ return x-'a';}void Insert(char *s){    int i,j,len=strlen(s);    int u=0;    for(i=0;i<len;i++){        int c=idx(s[i]);        if(!ch[u][c]){            memset(ch[sz],0,sizeof(ch[sz]));            val[sz]=0;            ch[u][c]=sz++;        }        u=ch[u][c];        word[u]++;    }    val[u]=1;}int Find(char *s){    int i,j,len=strlen(s);    int u=0;    for(i=0;i<len;i++){        int c=idx(s[i]);        if(!ch[u][c]) return 0;        u=ch[u][c];    }    return word[u];}int main(){    init();    while(gets(str)&&str[0]){ // 如果当前行为空行,s[0]='\0';        Insert(str);    }    while(scanf("%s",ask)!=EOF){        printf("%d\n",Find(ask));    }    return 0;}