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基础细节知识点
    JS数据类型的转换规则
    call,apply,求最大最小值,平均数等基础编程知识
    JS面向对象程序设计(OOP:Object Oriented Programming)
    C++ 手记
    C++ 在堆中申请内存方法
    vc驿站视频教程笔记4 Cstring 讲解
    vc驿站视频教程笔记2 ansi 和 unicode
  • 原文地址:https://www.cnblogs.com/mypsq/p/4348276.html
Copyright © 2011-2022 走看看