解题报告-HDOJ-1251(字典树)

    先给大家介绍一下什么是字典树。

    字典树,顾名思义,是树的一种,哈希树的变种,优点是节省存储空间,优化查询效率。

    数据结构:

 

typedef struct _node {

    Node *child[26];    //指向下一个字母,因为英文字母只有26个

    int n;   //表示前缀数目

    bool flag;   //表示是否以改字母结尾(按题目需要增加)

   ……  //其余内容可以根据题目要求进行增加
}Node;

 

下图是以ban,bag,bee,cat,cap,ca这6个单词构成的字典树:有三角形表示flag为true,没有表示false

 

字典树的插入操作:

void Insert (Node *root, char *str)
{//向以root为根的树中加入字符串str
    int len = strlen (str);
    Node *ans = root;
    for (int i =0; i < len; i ++)
    {
        if (ans->child[str[i] - 'a'] == NULL)//没有该字母
        {
            Node *NewNode = (Node *) malloc (sizeof (Node));    //建立节点
            //初始化
            NewNode->n = 1;
            for (int j = 0; j < 26; j++)
            {
                NewNode->child[j] = NULL;
            }

            ans->child[str[i] - 'a'] = NewNode;
            ans = NewNode;
        }
        else
        {
            ans = ans->child[str[i] - 'a'];  //找下一个字母
            ans->n ++;    //统计前缀数目
        }
    }
}

 

以下为1251的实现代码:

#include <iostream>

using namespace std;

char ch1[100000][20];
//char ch1[10][20];
char ch2[20];

typedef struct Node 
{
    Node *child[26];
    int n;
}Node;

void Insert (Node *root, char *str)
{
    int len = strlen (str);
    Node *ans = root;
    for (int i =0; i < len; i ++)
    {
        if (ans->child[str[i] - 'a'] == NULL)
        {
            Node *NewNode = (Node *) malloc (sizeof (Node));    
            NewNode->n = 1;
            for (int j = 0; j < 26; j++)
            {
                NewNode->child[j] = NULL;
            }
            ans->child[str[i] - 'a'] = NewNode;
            ans = NewNode;
        }
        else
        {
            ans = ans->child[str[i] - 'a'];
            ans->n ++;
        }
    }
}

int Search (Node *root, char *str)
{
    int len = strlen (str);
    Node *ans = root;
    int i;
    for (i = 0; i < len; i ++)
    {
        if (ans->child[str[i] - 'a'] != NULL)
        {
            ans = ans->child[str[i] - 'a'];
        }
        else
        {
            break;
        }
    }
    if (i == len)
    {
        return ans->n;
    }
    return 0;
}

int main ()
{
    Node *root = (Node *)malloc (sizeof (Node));
    root->n = 0;
    int i;
    for (i = 0; i < 26; i++)
    {
        root->child[i] = NULL;
    }

    i = 1;
    while (1) 
    {
        gets (ch1[i]);
        if (ch1[i][0] == 0)
        {
            break;
        }
        Insert (root, ch1[i]);
        i ++;
    }

    while (gets (ch2) != NULL)
    {    
        cout<<Search (root, ch2)<<endl;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值