[1251]统计难题(字典树) HDU

统计难题

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 131070/65535 K (Java/Others)
Total Submission(s): 18615    Accepted Submission(s): 8227

Problem Description
Ignatius最近遇到一个难题,老师交给他很多单词(只有小写字母组成,不会有重复的单词出现),现在老师要他统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀).
 

 

Input
输入数据的第一部分是一张单词表,每行一个单词,单词的长度不超过10,它们代表的是老师交给Ignatius统计的单词,一个空行代表单词表的结束.第二部分是一连串的提问,每行一个提问,每个提问都是一个字符串.

注意:本题只有一组测试数据,处理到文件结束.
 

 

Output
对于每个提问,给出以该字符串为前缀的单词的数量.
 

 

Sample Input
banana
band
bee
absolute
acm
 
ba
b
band
abc
Sample Output
2
3
1
0
 
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct node
{
    int flag;
    struct node *next[26];
};
struct node *creat()//建立新的节点
{
    struct node *p;
    p=(struct node *)malloc(sizeof(struct node));
    for(int i=0; i<26; i++)
    {
        p->next[i]=NULL;
        p->flag=1;
    }
    return p;
};
void inser(struct node *head,char *str)//插入法建立字典树
{
    struct node *p;
    int i,t;
    int len=strlen(str);
    p=head;
    for(i=0; i<len; i++)
    {
        t=str[i]-'a';
        if(p->next[t]==NULL)
        {
            p->next[t]=creat();
            p=p->next[t];
        }
        else
        {
            p->next[t]->flag++;
            p=p->next[t];
        }
    }
};
int fin(struct node *head,char *str)//查找
{
    int len=strlen(str);
    int i,t;
    struct node *p;
    p=head;
    for(i=0; i<len; i++)
    {
        t=str[i]-'a';
        if(p->next[t]==NULL)
            return 0;
        else
            p=p->next[t];
    }
    return p->flag;
}
int dele(struct node *head)//动态字典树,有时会超内存,这是就要记得释放空间了
{
    int i;
    if(head==NULL)
        return 0;
    for(i=0;i<26;i++)
    {
        if(head->next[i]!=NULL)
            dele(head->next[i]);
    }
    free(head);
    return 0;
}
int main()
{
    char str[20];
    struct  node *head;
    int num;
    head=(struct node *)malloc(sizeof(struct node));
    head=creat();
    while(gets(str)&&str[0]!='\0')
    {
        inser(head,str);
    }
    memset(str,0,sizeof(str));
    while(~scanf("%s",str))
    {
        num=fin(head,str);
        printf("%d\n",num);
    }
    dele(head);
    return 0;
}
posted @ 2014-09-14 20:26  jiangyy  阅读(102)  评论(0)    收藏  举报