HDU - 1251 統計難題
阿新 • • 發佈:2017-08-26
main ati col struct amp 單詞數 absolute err next
Ignatius最近遇到一個難題,老師交給他很多單詞(只有小寫字母組成,不會有重復的單詞出現),現在老師要他統計出以某個字符串為前綴的單詞數量(單詞本身也是自己的前綴).
Input輸入數據的第一部分是一張單詞表,每行一個單詞,單詞的長度不超過10,它們代表的是老師交給Ignatius統計的單詞,一個空行代表單詞表的結束.第二部分是一連串的提問,每行一個提問,每個提問都是一個字符串.
註意:本題只有一組測試數據,處理到文件結束.
Output對於每個提問,給出以該字符串為前綴的單詞的數量.
Sample Input
banana band bee absolute acm ba b band abc
Sample Output
2 3 1 0
字典樹裸題,註意沒給輸入大小很坑,暴力直接TLE
1 #include <stdio.h> 2 #include <string.h> 3 #include <iostream> 4 5 using namespace std; 6 7 struct node{ 8 int num; 9 node* next[26]; 10 node() 11 { 12 num=0; 13 for(int i=0;i<26;i++) 14 next[i]=NULL;15 } 16 }; 17 18 node* root=new node(); 19 node* rt; 20 int id,len; 21 22 void build(char* str) 23 { 24 rt=root; 25 len=strlen(str); 26 for(int i=0;i<len;i++) 27 { 28 id=str[i]-‘a‘; 29 if(rt->next[id]==NULL) 30 rt->next[id]=new node(); 31 rt=rt->next[id];32 rt->num++; 33 } 34 } 35 36 int querry(char* str) 37 { 38 rt=root; 39 len=strlen(str); 40 for(int i=0;i<len;i++) 41 { 42 id=str[i]-‘a‘; 43 if(rt->next[id]==NULL) 44 return 0; 45 rt=rt->next[id]; 46 } 47 return rt->num; 48 } 49 50 int main() 51 { 52 char str[15]; 53 while(gets(str)&&str[0]) 54 build(str); 55 while(gets(str)) 56 { 57 printf("%d\n",querry(str)); 58 } 59 return 0; 60 }
HDU - 1251 統計難題