Trie(字典)树

字典树

 Time Limit: 1000MS Memory Limit: 65536KB

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

参考博客:浅谈Trie树(字典树)

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <ctime>
#include <algorithm>
#include <vector>
#include <map>
#include <queue>
#include <stack>
using namespace std;
int i,n,root,tot,m;
bool stop[500010];
int trie[500010][27];
char s[15];
void insert(int root,char *s) //插入
{
    int i;
    int len = strlen(s);
    for(i = 0;i < len;i ++)
    {
        int id;
        id = s[i]-'a';
        if(!trie[root][id]) trie[root][id] = ++tot;
        root = trie[root][id];
    }
    stop[root] = 1; //结束标志
}
bool find(int root,char *s) //查询
{
    int i;
    int len = strlen(s);
    for(i = 0;i < len;i ++)
    {
        int id;
        id = s[i]-'a';
        if(!trie[root][id]) return 0;
        root = trie[root][id];
    }
    return stop[root];
}
int main()
{
    freopen("a.txt","r",stdin);
    ios::sync_with_stdio(0);
    while(cin>>n>>m)
    {
        if(!n&&!m) break;
        memset(trie,0,sizeof(trie));
        memset(stop,0,sizeof(stop));
        tot = 0;
        for(i = 1;i <= n;i ++)
        {
            cin>>s;
            insert(0,s);
        }
        for(i = 1;i <= m;i ++)
        {
            cin>>s;
            if(find(0,s)) cout<<"Yes"<<endl;
            else cout<<"No"<<endl;
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_30358129/article/details/79170218