我們二貨一樣的隊長大人居然在人人上發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()。不會捨棄空格,即使直接回車也會讀入一個空字符串。好物啊!必備啊!