字典树(f m)

版权声明:博主瞎写,随便看看 https://blog.csdn.net/LAN74__/article/details/55099617

日常一水题,字典树的基本构造。。。


啥都不用说了,直接上题
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 .
Example Input

3 2
aab
aa
ad
ac
ad
0 0

Example Output

No
Yes

很典型的字典树,我们可以直接一个结构体,里面放上24个指针(因为就只有小写字母)。。。。。然后来一个转化为对应数字,放进去,当有许多个指针的链表做就好啦

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct node 
{
    int sum;
    struct node *next[30];
}a[1000000];
int top;
struct node *creat()
{
    struct node *p = &a[top++];
    p -> sum = 0;
    for(int i = 0;i<26;i++)
    {
        p -> next[i] = NULL;
    }
    return p;
}
void insert(struct node *root,char *str)
{
    struct node *p = root;
    for(int i = 0;str[i]!='\0';i++)
    {
        int t = str[i] - 'a';
        if(p -> next[t] == NULL)
            p -> next[t] = creat();
        p = p -> next[t];
    }
    p -> sum ++;
}
int find(struct node *root,char *str)
{
    struct node *p = root;
    for(int i = 0;str[i]!='\0';i++)
    {
        int t = str[i] - 'a';
        if(p -> next[t] == NULL)
            return 0;
        p = p -> next[t];
    }
    return p -> sum;
}
int main()
{
    int n,m;
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        if(n==0&&m==0)
            break;
        top = 0;
        struct node *root = creat();//初始化一下。。。
        while(n--)
        {
            char str[100];
            scanf("%s",str);
            insert(root,str);
        }
        while(m--)
        {
            char str[100];
            scanf("%s",str);
            if(find(root,str))
                printf("Yes\n");
            else
                printf("No\n");
        }
    }
    return 0;
}

链表学好了这个也没啥问题。。。。。

猜你喜欢

转载自blog.csdn.net/LAN74__/article/details/55099617
M
^M