首页 > 学院 > 开发设计 > 正文

sdutacm-字典树

2019-11-06 06:21:06
字体:
来源:转载
供稿:网友

字典树

TimeLimit: 1000MS Memory Limit: 65536KB

SubmitStatistic

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

Hint

Author

gyx

SDUTACM

 

#include <iostream>#include<stdio.h>#include<string.h>#include<algorithm>#include<stdlib.h>#include<bits/stdc++.h>using namespace std;struct node{   int cnt;   int next[26];} tree[500005];int a;int creat(){   memset(tree[a].next,0,sizeof(tree[a].next));   tree[a].cnt =0;   return a++;}//用next数组名字本身存字母,数组中的数据存的是下一代节点位置void insert(int top,char *str){   int i,len,t;   for(i=0;str[i];i++)//每增加一个字母相当于多增加了一代   {       t = str[i]-'a';       if(tree[top].next[t]==0)//开辟下一代       {          tree[top].next[t]= creat();       }       top = tree[top].next[t];//存储完成进入下一代   }   ++tree[top].cnt;//cnt 则存储以当前字母结束字符串出现次数}int search(int top,char *str){   int i,t;   for(i=0;str[i];i++)   {      t = str[i]-'a';      if(tree[top].next[t]==0)//假如在树家族中后继无人,立即截止      {         return 0;      }      top = tree[top].next[t];//进入下一代,看似冲突的相同名字      //实际上占据了不同的空间,相同的建立查找规则使得冲突矛盾消失      //此时才取出字符串出现次数   }   return tree[top].cnt;}int main(){    char str[11];    int n,m,i,top;    while(~scanf("%d%d",&n,&m))    {        if(n==0&&m==0)        {            break;        }        a = 0;        top = creat();        for(i = 0;i< n;i++)        {            scanf("%s",str);            insert(top,str);        }        for(i = 0;i<m;i++)        {            scanf("%s",str);            if(search(top,str)==0)            printf("No/n");            else            printf("Yes/n");        }    }    return 0;}/***************************************************User name: jk160505徐红博Result: AcceptedTake time: 128msTake Memory: 1004KBSubmit time: 2017-02-10 10:33:19****************************************************/

 


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表