有道搜索框的代码--题解

19 篇文章 0 订阅
13 篇文章 0 订阅

[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树的裸题,处理时有些小细节,具体见代码

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<cstring>
#include<string>
using namespace std;
#define idx(x) x - 'a' + 1;
const int MAXN = 1e6+1000;
struct Tire {
    int next[28];
    int val;
    int flag;
}tree[MAXN];
char str[MAXN];
int nxt=1,n,m,cnt,S[100],tim=1;

void work(int,char *,int);

int add(){
    memset(&tree[nxt],0,sizeof(Tire));
    return nxt++;
}

void Insert(char *s){
    int rt=0,l=strlen(s);
    for (int i=0;i<l;++i){
        int num=idx(s[i]);      
        if (!tree[rt].next[num]) tree[rt].next[num]=add();
        rt=tree[rt].next[num];
    }
    tree[rt].val++;
}

bool Find(char *s){
    int rt=0,l=strlen(s);
    for (int i=0;i<l;++i){
        int num=idx(s[i]);
        if (!tree[rt].next[num]) return false;
        rt=tree[rt].next[num];
    }
    work(rt,s,1);
    return 1;
}

void work(int rt,char *s,int num){
    int k;
    for (k=1;k<=26;++k){
        if (cnt==8) return;
        S[num]=k;
        if (tree[rt].val&&tree[rt].flag!=tim) {
            cnt++; 
            tree[rt].flag=tim;
            printf("%s",s);
            for (int j=1;j<=num-1;++j)
               cout<<char(S[j]+'a'-1);
            cout<<" ";
        }
        if (tree[rt].next[k]){
            int p=tree[rt].next[k];//千万不要再用rt!!!
            work(p,s,num+1);
        }
    }
}

int main(){
    freopen("youdao.in","r",stdin);
    freopen("youdao.out","w",stdout);
    scanf("%d",&n);
    memset(&tree[0],0,sizeof(Tire));
    for (int i=1;i<=n;++i){
        scanf("%s",str); 
        Insert(str);
    }
    scanf("%d",&m);
    for (int i=1;i<=m;++i){
        scanf("%s",str);++tim;
        cnt=0; Find(str);
        if (!cnt) cout<<str<<endl;
           else cout<<endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值