hdu 1251 統計難題 (統計前綴出現次數)
阿新 • • 發佈:2019-01-27
統計難題
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 131070/65535 K (Java/Others)Total Submission(s): 46716 Accepted Submission(s): 16581
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 陣列要開四十萬才夠,一直在試資料大小,瘋狂re, 其實應該用malloc才對。
#include<iostream> #include<cstring> #include<cstdio> #include<algorithm> using namespace std; const int mx = 41e4 ; int tree[mx][26], sum[mx + 5]; int n ,tot, m; char te[15]; void add(char * str, int rt){ int x; for(int i = 0; str[i]; i++){ x = str[i] - 'a'; if(tree[rt][x] == 0) tree[rt][x] = ++tot; rt = tree[rt][x]; sum[rt]++; } } int find(char * str, int rt){ int x; for(int i = 0; str[i]; i++){ x = str[i] - 'a'; if(tree[rt][x] == 0) return 0; rt = tree[rt][x]; } return sum[rt]; } int main(){ // 因為只有一組資料所以不需要mem while (gets(te) && strlen(te)!= 0) add(te, 0); while(scanf("%s", te) != EOF) printf("%d\n",find(te, 0)); return 0; }