hdu1251 统计难题 字典树

来源:互联网 发布:按option无法切换mac 编辑:程序博客网 时间:2024/05/20 14:26

字典树模板题



#include<iostream>#include<cstdio>using namespace std;struct point{      point*  next[26];      int cot;   //count how many prefixes from root to current point.      point()   //constructor method, initialize 26 child of pointer      {          cot = 0;            memset(next,0,sizeof(next));      }};void insert(point *rt,char *s){     point p = rt;      int i=0;     int k;     while(s[i])     {          k = (s[i++]-'a');          if(p->next[k]==NULL)          {                p->next[k] = new point();          }          p->next[k]->cot++;          p = p->next;     }     return ;}int search(point *rt,char *s){      point p = rt;      int i = 0;      int k;      while(s[i])      {           k = s[i++]-'a';           if(p->next[k]==NULL) //the trie tree doesn't have the prefix           {                return 0;            }      }      return p->next[k]->cot;}int main(){    point *rt = new point();    char s[25];    while(gets(s)!=NULL)    {        if(s[0]=='\0')            break;        cout<<s<<endl;        insert(rt,s);    }    while(cin>>s)    {          cout<<search(rt,s)<<endl;    }    return 0;}
注意 要用c++交,不然MLE,不知道为什么

0 0
原创粉丝点击