HDU - 1251 字典树

czh将题库刷了若干遍之后,惊讶的发现自己的输入法已经完全存储了自己学过的所有单词,如果czh在该输入法中输入某个字符串,那么输入法会将所有以该字符串为前缀的英文单词作为备选项,为了对自己的英语水平有个客观的认识,czh想知道对于某个字符串一共有多少备选项 

Input

若干行,每行一个单词,长度不超过10,因为czh记忆力有限,保证只有小写字母,并且不会有重复的单词。一个空行表示结束。 又有若干行,每行一个提问表示czh输入的一个字符串。 

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

Output

对于每个提问,输出备选项数量 

Sample Input

inaccuracy
increase
impress
tolerant
tolerate

in
i
tole
int

Sample Output

2
3
2
0

这个题是个裸的字典树。数组模拟字典树。

主要注意一下读入的方法。

#include <bits/stdc++.h>
using  namespace std;
const int N = 5e5;
int tree[N][30];
int sum[N],tot;
char s[30];
void insert(){
    int root = 0,id,len;
    len = strlen(s);
    for (int i = 0; i < len; i++){
        id = s[i] - 'a';
        if (!tree[root][id]) tree[root][id] = ++tot;
        sum[tree[root][id]]++;
        root = tree[root][id];
    }
    return;
}
int find(){
    int id,root = 0,len;
    len = strlen(s);
    for (int i = 0; i < len; i++){
        id = s[i] - 'a';
        if (!tree[root][id]) return 0;
        root = tree[root][id];
    }
    return sum[root];
}

int main() {
    while(gets(s)){
        if (s[0] == NULL) break;  //空行。gets读入的回车符会自动转换为NULL。
        insert();
    }
    while(scanf("%s",s) != EOF){
        if (s[0]=='\0') break;
        printf("%d\n",find());
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/kidsummer/article/details/81095867