hdoj 1251 统计难题(字典树)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1251

思路分析:该问题要求求出以某个字符串为前缀的单词数目,通过使用字典树,在字典树中添加count记录通过该结点的单词数目即可;

查找时找到前缀的最后一个单词的结点的count值即为所求;

代码如下:

#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;

const int KIND = 26;
const int MAX_N = 20;
struct Node
{
    Node *next[26];
    int count;
    Node ()
    {
        count = 0;
        memset(next, 0, sizeof(next));
    }
};

void InsertTrie(Node *root, char *str)
{
    Node *p = root;
    int i = 0, k = 0;

    while (str[i])
    {
        k = str[i] - 'a';
        if (!p->next[k])
            p->next[k] = new Node();
        p = p->next[k];
        p->count++;
        ++i;
    }
}

int Find(Node *root, char *str)
{
    int i = 0, k = 0;
    Node *p = root;

    while (str[i])
    {
        k = str[i] - 'a';
        if (!p->next[k])
            return 0;
        p = p->next[k];
        ++i;
    }
    return p->count;
}

int main()
{
    int ans = 0;
    char str[MAX_N];
    Node *root = new Node();

    while (gets(str) && strcmp(str,"") != 0)
        InsertTrie(root, str);
    while (gets(str))
    {
        ans = Find(root, str);
        printf("%d
", ans);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/tallisHe/p/4663051.html