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()。不會捨棄空格,即使直接回車也會讀入一個空字符串。好物啊!必備啊!


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