zoukankan      html  css  js  c++  java
  • 字典树

    #include"string.h"
    #include"stdio.h"
    #include"queue"
    #include"iostream"
    #include"stdlib.h"
    #define M 10001
    using namespace std;
    struct node
    {
         int next[28];//记录当前字母编号的儿子字母编号
         int w;//记录每个单词的编号(按照输入的顺序)
    }tree[M];
    int index;
    void creat(int k,char *ch)
    {
         int len=strlen(ch);
         int i,s=0;
         for(i=1;i<=len;i++)
         {
              int m=ch[i-1]-'a'+1;
              if(tree[s].next[m]==0)
              {
                   if(i==len)
                        tree[index].w=k;//当读取到一个单词的最后一个字母是把该单词编号为k
                   tree[s].next[m]=index++;//index记录的是每个单词中每个字母的编号
              }
              else
              {
                   if(i==len)
                        tree[tree[s].next[m]].w=k;//该种情况是读取了相同的单词
              }
              s=tree[s].next[m];//把该单词的编号延续到下一个
         }
    }
    int finde(char *ch)
    {
         int len=strlen(ch);
         int i,s=0;
         for(i=1;i<=len;i++)
         {
              int m=ch[i-1]-'a'+1;
              if(tree[s].next[m]!=0)
              {
                   if(i==len&&tree[tree[s].next[m]].w!=0)
                        return 1;//若returne tree[tree[s].next[m]].w即返回该单词的序号
                   s=tree[s].next[m];
              }
              else
                   return 0;
         }
         return 0;
    }
    int main()
    {
         int i,n;
         char ch[222];
         scanf("%d",&n);
         index=1;
         memset(tree,0,sizeof(tree));
         for(i=1;i<=n;i++)
         {
              scanf("%s",ch);
              creat(i,ch);
         }
         while(scanf("%s",ch)!=-1)
         {
              int ans=finde(ch);
              if(ans)
                   printf("Find!
    ");
              else
                   printf("No find!
    ");
         }
         return 0;
    }
    /*
    10
    change
    charge
    agony
    agreement
    competent
    complex
    compose
    expose
    handy
    handle
    
    
    change
    Find!
    charge
    Find!
    agony
    Find!
    agreement
    Find!
    competent
    Find!
    complex
    Find!
    compose
    Find!
    handy
    Find!
    handle
    Find!
    yang
    No find!
    pose
    No find!
    */

  • 相关阅读:
    The following untracked working tree files would be overwritten by merge
    如何删除git远程仓库项目的所有内容,重新提交所有内容
    Vue中引入bootstrap导致的CSS问题
    CSS实现垂直居中
    RESTful三问
    SAPUI5 freestyle vs SAP Fiori Elements —— 两种开发SAPUI5 Apps的方式对比
    团队1
    用户规格说明书
    MElv2.kkkK
    ME.kkkK
  • 原文地址:https://www.cnblogs.com/mypsq/p/4348276.html
Copyright © 2011-2022 走看看