现在的位置: 首页 > 综合 > 正文

hdu 1251 统计难题 (字典树)

2012年03月09日 ⁄ 综合 ⁄ 共 1504字 ⁄ 字号 评论关闭

统计难题

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 131070/65535 K (Java/Others)

Total Submission(s): 13884    Accepted Submission(s): 5971
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 <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#define MAX 26
using namespace std;

int n,m;
char ss[1005];
struct Trie                  //Trie结点声明
{
    int isStr;               //记录该结点处有多少单词经过
    Trie *next[MAX];         //儿子分支
};

void insert(Trie *root,const char*s)    //将单词s插入到字典树中
{
    if(root==NULL||*s=='\0') return;
    int i;
    Trie *p=root;
    while(*s!='\0')
    {
        if(p->next[*s-'a']==NULL)       //如果不存在,则建立结点
        {
            Trie *temp=(Trie *)malloc(sizeof(Trie));
            for(i=0; i<MAX; i++)
            {
                temp->next[i]=NULL;
            }
            temp->isStr=1;
            p->next[*s-'a']=temp;
            p=p->next[*s-'a'];
        }
        else
        {
            p=p->next[*s-'a'];
            p->isStr++;
        }
        s++;
    }
}
int search(Trie *root,const char*s)
{
    Trie *p=root;
    while(p!=NULL&&*s!='\0')
    {
        p=p->next[*s-'a'];
        s++;
    }
    if(p!=NULL)  return p->isStr;
    return 0;
}
void del(Trie *root)                     //释放整个字典树占的堆区空间
{
    int i;
    for(i=0; i<MAX; i++)
    {
        if(root->next[i]!=NULL)
        {
            del(root->next[i]);
        }
    }
    free(root);
}
int main()
{
    int i;
    Trie *root= (Trie *)malloc(sizeof(Trie));
    for(i=0; i<MAX; i++)
    {
        root->next[i]=NULL;
    }
    root->isStr=0;
    while(1)
    {
        gets(ss);
        if(strlen(ss)==0||ss[0]==' ') break ;
        insert(root,ss);
    }
    while(gets(ss)!=NULL)
    {
        printf("%d\n",search(root,ss));
    }
    del(root);                        //释放空间很重要
    return 0;
}
/*
alloc
all
allo
al

a
l
all
*/
 

抱歉!评论已关闭.