您的位置:首页 > 理论基础 > 数据结构算法

数据结构 字典树模板

2013-11-28 15:29 447 查看
#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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: