hdu 5.2.1 统计难题

我们二货一样的队长大人居然在人人上发acm做的题……闹哪样啊!嫌某人刷英语单词的行径不够值得吐槽么??!!纯脑残啊这是!真丢脸……开个博客会怀孕么……

枉我含辛茹苦的说服了那么久居然还不肯删掉日志……要不要这样啊……

正题……

统计难题

Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 131070/65535 K (Java/Others)
Total Submission(s): 64 Accepted Submission(s): 48
 
Problem Description
Ignatius最近遇到一个难题,老师交给他很多单词(只有小写字母组成,不会有重复的单词出现),现在老师要他统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀).
 
Input
输入数据的第一部分是一张单词表,每行一个单词,单词的长度不超过10,它们代表的是老师交给Ignatius统计的单词,一个空行代表单词表的结束.第二部分是一连串的提问,每行一个提问,每个提问都是一个字符串.

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

            对于每个提问,给出以该字符串为前缀的单词的数量.
 
Sample Input
banana
band
bee
absolute
acm

ba
b
band
abc
 
Sample Output
2
3
1
0
 

如今每进入一个新的章节我都提心吊胆的……因为这意味着又要出现新的知识点了……所以我完全不考虑朴素的算法了,必须超时超到泪流啊……

不过配着题看,尤其是这种模板题,觉得以前难以企及的知识点也不是那么完全理解不能嘛哈哈~~~~^-^~~~~

这题就是trie树的纯模版,因为trie树本来也就叫字典树嘛……

#include <iostream>
#include <cstring>
#include <string>
#include<cstdlib>
using namespace std;
#define MAX 26
struct trie
{
       int prefix;//how many words start from this 
       trie *next[MAX];//26 branch
};

void insert(trie *root,char *s)
{
     int i;
     trie *p=root;
     while(*s!='\0')
     {
         if(p->next[*s-'a']==NULL)//no one start from this 
         {
             trie *temp=new trie;//son tree
             for(i=0;i<MAX;i++)
             {
                 temp->next[i]=NULL;//initiate
             }
             temp->prefix=1;//there is one word start from this now
             p->next[*s-'a']=temp;
             p=p->next[*s-'a'];
         }
         else
         {
             p=p->next[*s-'a'];
             p->prefix++;//one more word start from this
         }
         s++;//next character
     }
}

int count(trie *root,char *pre)
{
    trie *p=root;//won't change root
    while(*pre!='\0')//the pre-word isn't over
    {
        if(p->next[*pre-'a']==NULL)//no word start from this 
            return 0;
        else
        {
            p=p->next[*pre-'a'];
            pre++;//next character
        }
    }
    return p->prefix;
}


void del(trie root){}

int main()
{
    int i;
    char s[12];
    trie *root= new trie;
    for(i=0;i<MAX;i++)
    {
        root->next[i]=NULL;
    }
    root->prefix=0;
    while(1)
    {
           // cin>>s;
           gets(s);
            if(strcmp(s,"")==0)
                break;
            insert(root,s);
    }
    while(getline(cin,s))
    {
        cout<<count(root,s)<<endl;
    }
  //  del(root);
    return 0;
}
    
    
    
通过这题还学到了gets()。不会舍弃空格,即使直接回车也会读入一个空字符串。好物啊!必备啊!


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章