字典树

来源:互联网 发布:caffe cudnn 编辑:程序博客网 时间:2024/06/06 16:26

代码:

char s[N];typedef struct node{    struct node *n[33];    int cnt;    node()    {        cnt = 0;        memset(n, 0, sizeof(n));    }}Q, *T;T root = new node();void Creat(){    T p = root;    for(int i = 0; s[i]; i++)    {        int id = s[i] - 'a';        if(p->n[id] == NULL)        {            p->n[id] = new node();        }        p = p->n[id];        p->cnt++;    }}int Find(){     T p = root;     for(int i = 0; s[i]; i++)     {         int id = s[i] - 'a';         if(p->n[id] == NULL)            return 0;         p = p->n[id];     }     return p->cnt;}void F(T S){    if(S == NULL) return ;    for(int i = 1; i <= 26; i++)    {        if(S->n[i])            F(S->n[i]);    }    delete S;    S = NULL;}int main(){    while(gets(s), s[0] != '\0')    {        Creat();    }    while(gets(s))    {        int ans = Find();        cout << ans << endl;    }    F(root);    return 0;}