动态字典树_统计前缀子串(HDU_1251)

#include <stdio.h>
#include <string.h>

#define M 26

struct node{
    int count;
    node *child[M];
    node()
    {
        count = 0;
        memset(child,NULL,sizeof(child));
    }
};

void clear(node *root)
{
    for(int i=0; i<M; i++)
    {
        if(root->child[i] != NULL)
            clear(root->child[i]);
    }
    delete root;
}

void insert(node *root, char *str)
{
    node *p = root;
    int len = strlen(str);
    for(int i=0; i<len; i++)
    {
        int k = str[i] - 'a';
        if(p->child[k] ==NULL)
            p->child[k] = new node;
        p->child[k]->count++;
        p = p->child[k];
    }
}

int find(node *root, char *str)
{
    node *p = root;
    int len = strlen(str);
    for(int i=0; i<len; i++)
    {
        int k = str[i] - 'a';
        if(p->child[k] == NULL)
            return 0;
        p = p->child[k];
    }
    return p->count;
}

int main(int argc, char* argv[])
{
    #ifdef __MYLOCAL
    freopen("in.txt","r",stdin);
    #endif

    char id[M];
    node *root = new node;
    while(gets(id) && id[0] != '')
    {
        insert(root,id);
    }
    while(scanf("%s",id) != EOF)
    {
        printf("%d
",find(root,id));
    }

    clear(root);

    return 0;
}
原文地址:https://www.cnblogs.com/lk1993/p/3207388.html