数据结构 字典树模板

来源:互联网 发布:海岛奇兵 多管升级数据 编辑:程序博客网 时间:2024/04/29 04:23
#include "stdio.h" // 字典树模板  hdu 1251#include "string.h"#include "stdlib.h"struct node{    struct node *next[26];    int num;};struct node *root;void insert(char *k){    int i;    struct node *a = root;    while(k[0]!='\0')    {        if(a->next[k[0]-'a'] == NULL)        {            node *tt;            tt = (node *)malloc(sizeof(node));            tt->num = 1;            for(i=0;i<26;i++) tt->next[i] = NULL;            a->next[k[0]-'a'] = tt;            a = tt;  //移向下一级        }        else        {            a = a->next[k[0]-'a'];  //移向下一级            a->num = a->num + 1;        }        k++;    }}int find(char *k){    int ans;    struct node *a = root;    while(k[0]!='\0')    {        if(a->next[k[0]-'a']==NULL)            return 0;        else        {            ans = a->next[k[0]-'a']->num;            a = a->next[k[0]-'a'];        }        k++;    }    return ans;}void BFS(node *k);int main(){    int i;    char str[15];    root = (node *)malloc(sizeof(node));  //给root指针开辟空间    for(i=0;i<26;i++)  //root下的指针初始化        root->next[i] = NULL;    root->num = 0;    while(gets(str) && strcmp(str,"")!=0)        insert(str);    while(scanf("%s",str)!=-1)        printf("%d\n",find(str));    BFS(root);    return 0;}void BFS(node *k)  //深搜去释放内存!{    int i;    if(k==NULL)    return ;    for(i=0;i<26;i++)    {        if(k->next[i]!=NULL)            BFS(k->next[i]);    }    free(k);}

原创粉丝点击