統計難題
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 131070/65535 K (Java/Others)
Total Submission(s): 24570 Accepted Submission(s): 10153
Problem Description
Ignatius最近遇到一個難題,老師交給他很多單詞(只有小寫字母組成,不會有重復的單詞出現),現在老師要他統計出以某個字符串為前綴的單詞數量(單詞本身也是自己的前綴).
Input
輸入數據的第一部分是一張單詞表,每行一個單詞,單詞的長度不超過10,它們代表的是老師交給Ignatius統計的單詞,一個空行代表單詞表的結束.第二部分是一連串的提問,每行一個提問,每個提問都是一個字符串.
注意:本題只有一組測試數據,處理到文件結束.
注意:本題只有一組測試數據,處理到文件結束.
Output
對於每個提問,給出以該字符串為前綴的單詞的數量.
Sample Input
banana band bee absolute acm ba b band abc
Sample Output
2 3 1 0
Author
Ignatius.L
Recommend
Ignatius.L
這題其實可以用字典樹模板直接做,不過值得注意的是,如果用G++交下面的代碼的話會超內存,而用C++交就能通過,具體原因不太清楚,個人覺得可能是G++會在申請指針內存的同時也會申請一個指針對應的類型大小的內存。也有看到用G++交過了的,看了他的代碼,沒有動態生成子節點,而是開了100萬多的結構體數組,模擬指針。

#include <stdio.h> #include <string.h> #include <iostream> using namespace std; struct node{ int num; node* next[26]; node() { num=0; memset(next,NULL,sizeof(next)); } }; node* root=new node(); node* rt; int id,len; void build(char str[30]) { rt=root; len=strlen(str); for(int i=0;i<len;i++) { id=str[i]-'a'; if(rt->next[id]==NULL) rt->next[id]=new node(); rt=rt->next[id]; rt->num++; } } int querry(char str[30]) { rt=root; len=strlen(str); for(int i=0;i<len;i++) { id=str[i]-'a'; if(rt->next[id]==NULL) return 0; rt=rt->next[id]; } return rt->num; } int main() { char str[30]; while(gets(str)&&str[0]) { build(str); } while(gets(str)) { printf("%d\n",querry(str)); } return 0; }