字典树

本文介绍了一种使用字典树(Trie)的数据结构来高效查询单词的方法。通过构建字典树,可以快速判断一系列查询单词是否存在于字典中。文章提供了完整的C++代码实现,包括字典树节点的创建、插入单词以及查找单词等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

字典树

Time Limit: 1000 ms Memory Limit: 65536 KiB

Problem Description

遇到单词不认识怎么办? 查字典啊,已知字典中有n个单词,假设单词都是由小写字母组成。现有m个不认识的单词,询问这m个单词是否出现在字典中。

Input

含有多组测试用例。

第一行输入n,m (n>=0&&n<=100000&&m>=0&&m<=100000)分别是字典中存在的n个单词和要查询的m个单词.

紧跟着n行,代表字典中存在的单词。

然后m行,要查询的m个单词

n=0&&m=0 程序结束

数据保证所有的单词都是有小写字母组成,并且长度不超过10

Output

若存在则输出Yes,不存在输出No .

Sample Input

3 2
aab
aa
ad
ac
ad
0 0

Sample Output

No
Yes

题目链接:

http://acm.sdut.edu.cn/onlinejudge2/index.php/Home/Contest/contestproblem/cid/2715/pid/2828.html

#include <bits/stdc++.h>

using namespace std;

typedef struct trietree{
    int num;
    struct trietree *next[26];
}tree;

int top=-1;
tree memory[1000000];//static memory申请

tree *create_full()
{
    tree *root=&memory[++top];
    root->num=0;
    for(int i=0;i<26;i++)
    {
        root->next[i]=NULL;
    }
    return root;
}

tree *create(tree *root,char *str)
{
    tree *p=root;
    for(int i=0;str[i]!='\0';i++)
    {
        int k=str[i]-'a';
        if(!p->next[k])
        {
            p->next[k]=create_full();
        }
        p=p->next[k];
    }
    p->num++;
    return root;
}

int find(tree *root,char *str)
{
    tree *p=root;
    for(int i=0;str[i]!='\0';i++)
    {
        int k=str[i]-'a';
        if(!p->next[k])
        {
            return 0;
        }
        p=p->next[k];
    }
    return p->num;
}

int main()
{
    int n,m;
    while((cin >> n >> m)&&(n || m))
    {
        top=-1;//方便分配静态内存
        tree *root;
        root=create_full();
        char str[16];
        while(n--)
        {
            cin >> str;
            root=create(root,str);
        }
        while(m--)
        {
            cin >> str;
            if(find(root,str))
            {
                cout << "Yes" << endl;
            }
            else
            {
                cout << "No" << endl;
            }
        }
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值