SDUTOJ2828_字典树

字典树

Time Limit: 1000 ms Memory Limit: 65536 KiB

Submit Statistic

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

Hint

Source

gyx

 

#include <bits/stdc++.h>
using namespace std;
struct tree
{
    int cnt;
    tree *nextt[26];
};
tree T[1000000]; // 申请静态内存
int top;
tree *creat() // 创建下一代
{
    tree *p = &T[top++];
    for (int i = 0; i < 26; i++)
        p->nextt[i] = NULL;
    p->cnt = 0;
    return p;
}

void insert(tree *root, char *str) // 插入单词构建字典
{
    tree *p = root;
    for (int i = 0; i < strlen(str); i++)
    {
        int index = str[i] - 'a';    // index 索引字符str[i]在26字母中的顺序
        if (p->nextt[index] != NULL) // 当这一位置已经有了这个字符的时候 进入下一代
        {
            p = p->nextt[index]; // 进入判断下一层index位置是否有元素
            continue;
        }
        else // 当这一位置没有有这个字符的时候 开辟下一代并存入将此字符当代
        {
            p->nextt[index] = creat();
            p = p->nextt[index];
        }
    }
    p->cnt = 1; // 标记这里存完一个单词 便于后序查找
    //return 0;
}

int search(tree *root, char *str)
{
    tree *p = root;
    for (int i = 0; i < strlen(str); i++)
    {
        int index = str[i] - 'a';
        if (p->nextt[index] != NULL) // 匹配到该字母 进入下一层
            p = p->nextt[index];
        else // 匹配不到终止
            return 0;
    }
    /*所有字母都已经匹配到了 判断是否存在改单词*/
    if (p->cnt == 1) // 存在
        return 1;
    else // 不存在返回0
        return 0;
}
int main()
{
    int n, m;
    char s[11];

    while (~scanf("%d %d", &n, &m))
    {
        if (m == 0 && n == 0)
            break;
        top = 0;
        tree *root = creat();
        for (int i = 0; i < n; i++)
        {
            scanf("%s", s);
            insert(root, s);
        }
        for (int i = 0; i < m; i++)
        {
            scanf("%s", s);
            int ans = search(root, s);
            if (ans == 1)
                printf("Yes\n");
            else
                printf("No\n");
        }
    }

    return 0;
}

 

转载于:https://www.cnblogs.com/iQXQZX/p/10258769.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值