hdu1251 统计难题(字典树)

来源:互联网 发布:win7 mac地址修改 编辑:程序博客网 时间:2024/05/16 09:38

题目链接:hdu1251

基本的字典树,字典树又称单词查找树,Trie树,是一种树形结构,是一种哈希树的变种。典型应用是用于统计,排序和保存大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。它的优点是:利用字符串的公共前缀来节约存储空间,最大限度地减少无谓的字符串比较,查询效率比哈希表高。


#include <iostream>#include <cstdio>#include <algorithm>#include <cstring>#include <cmath>#include <cstdlib>using namespace std;const int inf = 99999999;const int N = 105;struct node{    int count;    node *next[26];}*root;node *build()//建立结点{    node *p = (node *)malloc(sizeof(node));    for(int i = 0; i < 26; i ++)        p -> next[i] = NULL;    p -> count = 1;    return p;}void save(char *s){    int len = strlen(s);    node *p;    p = root;    for(int i = 0; i < len; i ++)    {        if(p -> next[s[i] - 'a'] != NULL)//该前缀以存在,则计数加1        {            p = p -> next[s[i] - 'a'];            (p -> count)++;        }        else//不存在,则建立新的结点        {            p -> next[s[i] - 'a'] = build();            p = p -> next[s[i] - 'a'];        }    }}int query(char *s){    int len = strlen(s);    node *p;    p = root;    for(int i = 0; i < len; i ++)    {        if(p -> next[s[i] - 'a'] == NULL)//该前缀不存在            return 0;        p = p -> next[s[i] - 'a'];    }    return p -> count;}int main(){    char str[15];    root = build();    while(gets(str),str[0] != '\0')        save(str);    while(~scanf("%s",str))        printf("%d\n",query(str));    return 0;}


0 0
原创粉丝点击