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!
    */

  • 相关阅读:
    踏实每一个脚印——2019年12月复盘
    修改博客园markdown编辑器代码高亮风格的方法
    Hyperion: Building the Largest In memory Search Tree
    C++11——智能指针
    拷贝控制
    分布式系统常见概念
    extern和static使用
    APUE—UNIX文件系统
    C++的一些细节
    fork和僵尸进程
  • 原文地址:https://www.cnblogs.com/mypsq/p/4348276.html
Copyright © 2011-2022 走看看