zoukankan      html  css  js  c++  java
  • Cogs 647. [Youdao2010] 有道搜索框(Trie树)

    1. [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.
    不过加了一个print过程.
    建树记一下单词结尾. 
    构造一个串输出即可.
    */
    #include<iostream>
    #include<cstdio>
    #include<cstring>
    #define MAXN 100001
    using namespace std;
    int n,m,tot;
    char ss[MAXN],ch[MAXN];
    struct data{int next[27],tot;bool b;}tree[MAXN*2];
    void add(char s[],int l)
    {
        int now=0;
        for(int i=0;i<l;i++)
        {
            int x=s[i]-96;
            if(tree[now].next[x]) now=tree[now].next[x];
            else tot++,tree[now].next[x]=tot,now=tot;
        }
        tree[now].b=true;
    }
    void dfs(int now,int &sum,int len)
    {
        if(sum>=8) return ;
        if(tree[now].b) sum++,printf("%s ",ch);
        for(int i=1;i<=26;i++)
        {
            if(tree[now].next[i]) 
            {
                ch[len]=i+96;
                dfs(tree[now].next[i],sum,len+1);
                ch[len]=0;
            }
        }
    }
    void query(char s[],int l)
    {
        int now=0,sum=0,x;
        for(int i=0;i<l;i++)
        {
            x=s[i]-96;
            if(!tree[now].next[x]){cout<<s<<endl;return ;}
            now=tree[now].next[x];
        }
        memset(ch,0,sizeof ch);
        for(int i=0;i<l;i++) ch[i]=s[i];
        dfs(now,sum,l);
        printf("
    ");
    }
    int main()
    {
        freopen("youdao.in","r",stdin);
        freopen("youdao.out","w",stdout);
        scanf("%d",&n);
        for(int i=1;i<=n;i++)
        {
            cin>>ss+1;
            int l=strlen(ss+1);
            add(ss+1,l);
        }
        scanf("%d",&m);
        for(int i=1;i<=m;i++)
        {
            cin>>ss+1;
            int l=strlen(ss+1);
            query(ss+1,l);
        }
        return 0;
    }
  • 相关阅读:
    eclipse c++
    smb
    osx mount nfs/smb
    0927用的
    0926 隐藏地址栏
    0921笔记
    生成文件并下载
    在线图标
    react redux
    electron
  • 原文地址:https://www.cnblogs.com/nancheng58/p/10068130.html
Copyright © 2011-2022 走看看