【Trie】【cogs647】有道搜索框

647. [Youdao2010] 有道搜索框

★☆
输入文件:youdao.in   输出文件:youdao.out   简单对比
时间限制:1 s   内存限制:128 MB

【问题描述】
在有道搜索框中,当输入一个或者多个字符时,搜索框会出现一定数量的提示,如下图所示:
这里写图片描述
现在给你 N 个单词和一些查询,请输出提示结果,为了简这个问题,只需要输出以查询词为前缀的并且按字典序排列的最前面的 8 个单词,如果符合要求的单词一个也没有请只输出当前查询词。

【输入文件】
第一行是一个正整数 N ,表示词表中有 N 个单词。
接下来有 N 行,每行都有一个单词,注意词表中的单词可能有重复,请忽略掉重复单词。所有的单词都由小写字母组成。
接下来的一行有一个正整数 Q ,表示接下来有 Q 个查询。
接下来 Q 行,每行有一个单词,表示一个查询词,所有的查询词也都是由小写字母组成,并且所有的单词以及查询的长度都不超过 20 ,且都不为空
其中: N<=10000,Q<=10000

【输出文件】
对于每个查询,输出一行,按顺序输出该查询词的提示结果,用空格隔开。

【样例输入】
youdao.in

10 
a 
ab 
hello 
that 
those 
dict 
youdao 
world 
your 
dictionary 
6 
bob 
d 
dict 
dicti 
yo 
z 

【样例输出】
youdao.out

bob 
dict dictionary 
dict dictionary 
dictionary 
youdao your 
z

题解:
写一棵trie。对于每一组询问先判断一下是否存在这样一个单词,若存在就开始搜,每搜到一个符合的单词就输出来。
Code:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<algorithm>
using namespace std;
char c[30],b[100];
int n,q,ans,num;
struct Trie{
    Trie *son[28]; char ch; bool f;
    Trie(char cc){
        for (int i=0; i<26; i++) son[i]=NULL;
        f=false; ch=cc;
    }
}*root;
void Insert(Trie *x,int w,int len){
    int v=c[w]-'a';
    if (!x->son[v]){
        Trie *y=new Trie(c[w]);
        x->son[v]=y; x=x->son[v];
    }
    else x=x->son[v];
    if (w==len-1){
        x->f=true;
        return;
    }
    Insert(x,w+1,len);
}
bool Judge(Trie *x,int w,int len){
    if (w==len) return true;
    int v=c[w]-'a';
    if (!x->son[v]) return false;
    else Judge(x->son[v],w+1,len);
}
void Query(Trie *x,int w,int len){
    if (w<len)
        Query(x->son[c[w]-'a'],w+1,len);
    else {
        if (x->f && ans<8){
            for (int i=0; i<num; i++) printf("%c",b[i]);
            if (w!=len) printf("%c ",x->ch); ans++;
//          cout<<num<<"  "<<ans<<endl;
        }
        for (int i=0; i<26; i++)
            if (x->son[i] && ans<8){
                if (w>len) b[num++]=x->ch;
//              cout<<num<<"  "<<ans<<endl;
                Query(x->son[i],w+1,len);
                if (w>len) num--;
//              cout<<num<<"  "<<ans<<endl;
            }
    }
}
int main(){
    scanf("%d",&n);
    root=new Trie(' ');
    for (int i=1; i<=n; i++){
        scanf("%s",&c);
        Insert(root,0,strlen(c));
    }
    scanf("%d",&q);
    while (q--){
        scanf("%s",&c); int len=strlen(c);
        if (!Judge(root,0,len)) printf("%s",c);
        else {
            num=len,ans=0; strcpy(b,c);
            Query(root,0,len);
        }
        printf("\n");
    }
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值