首页 > 其他 > 详细

hdu1251 统计难题(字典树)

时间:2014-02-18 14:47:22      阅读:385      评论:0      收藏:0      [点我收藏+]

题目链接:hdu1251

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

bubuko.com,布布扣

#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;
}


hdu1251 统计难题(字典树)

原文:http://blog.csdn.net/jzmzy/article/details/19394525

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!