http://acm.hdu.edu.cn/showproblem.php?pid=1251&&字典树

来源:互联网 发布:商务印书馆 知乎 编辑:程序博客网 时间:2024/06/05 23:43

字典树水题,求公共前缀的个数。。。

#include<iostream>#include<string.h>#include<string>#include<stdlib.h>using namespace std;typedef struct Tire{int count; struct Tire *next[26];}*Node,T;Node a;void init(){a=(Node)malloc(sizeof(T));for(int i=0;i<26;++i)a->next[i]=NULL;}void insert(string s){  Node head=a;int n=s.size();for(int i=0;i<n;++i){int k=(int)(s[i]-97);if(head->next[k]==NULL){head->next[k]=new T;head=head->next[k];head->count=1;for(int i=0;i<26;++i)head->next[i]=NULL;}else   {          head=head->next[k]; head->count++;       }}}int find(string s){int n=s.size();Node head=a;for(int i=0;i<n;++i){int  k=(int)(s[i]-97);if(head->next[k])   head=head->next[k];else  return 0;}return head->count;}int main(){ char ch[10]; init();while(gets(ch),strcmp(ch,""))insert(ch);while(gets(ch))cout<<find(ch)<<endl;return 0;}


原创粉丝点击