1251 trie树(返回前缀数)(我对find函数进行啦修改)

来源:互联网 发布:python frozenset 编辑:程序博客网 时间:2024/06/10 07:20
#include <iostream>#include <algorithm>#include <string>using namespace std;typedef struct dictor DIC;DIC *root = NULL;//初始化,呵呵struct dictor {       dictor (){ num=0;exist = false; memset ( child , 0 , sizeof ( child ) ); }//初始化函数很重要       void insert ( char *ins );       int find ( const char *ins );private:       DIC *child[26];       bool exist;public:   int num;};//插入函数void dictor::insert ( char *ins ){            DIC *cur = root,*now;            int len = strlen ( ins );            for ( int i = 0; i < len; ++ i )            {                  if ( cur->child[ ins[i] - 'a' ] != NULL )//如果说这个点已经有元素啦                  {   cur->child[ins[i] - 'a' ]->num++;                       cur = cur->child[ ins[i] - 'a' ];//移动游标                  }                  else                  {                       now = new DIC;//新建一个节点   now->num=1;                       cur->child[ ins[i] - 'a' ] = now;//把这个节点加到trie树中                       cur = now;//把当前位置保存下来给游标,用来存放下一个元素                     }            }             cur->exist = true;}//查找函数int dictor::find ( const char *ins ){            DIC *cur = root;            int len = strlen ( ins );            for ( int i = 0; i < len; ++ i )            {                 if ( cur->child[ ins[i] - 'a' ] != NULL )//如果这个点存在                      cur = cur->child[ ins[i] - 'a' ];//移动游标                   else                      //return false; //返回失败  return 0;            }return cur->num;}char words[12];//char words[20][100];DIC dict;int main(){//freopen("input.txt","r",stdin);root=&dict;int n=0;while(1){gets(words);if(words[0]<'a'||words[0]>'z')break;dict.insert(words);}char temp[12];while(scanf("%s",temp)!=EOF){cout<<dict.find(temp)<<endl;}return 0;}/*1 开始的时候我定义为words[3000][12];会av,于是我修改该为words[12],让后就过啦。*/

原创粉丝点击