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

  • 相关阅读:
    境外支付宝接口对接--支付接口
    js bind
    css的input文本框的 propertychange、focus、blur
    字符流Reader和Writer
    对象流--对象的序列化
    输入流IS和输出流OS学习总结
    File文件的读写操作RandomAccessFile类
    File文件操作学习总结
    Map集合的便利学习总结
    Map集合学习总结
  • 原文地址:https://www.cnblogs.com/mypsq/p/4348276.html
Copyright © 2011-2022 走看看