码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-08-10 13:41:12      阅读:114      评论:0      收藏: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;
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

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

标签:题解   有道   模板   

原文地址:http://blog.csdn.net/qq_27138357/article/details/47396573

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!