1. 程式人生 > >HDU 1251 統計難題

HDU 1251 統計難題

show size ott fin com 自己 class tdi sam

統計難題

Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 131070/65535 K (Java/Others)
Total Submission(s): 41049 Accepted Submission(s): 14833


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 | We have carefully selected several similar problems for you: 1075 1247 1671 1298 1800 trie 樹,求前綴數量之和,挺裸的
#include<cstdio>
#include
<cstring> using namespace std; #define N 500000 struct node{ bool have; int son[26]; int cnt; int acnt; node(){ have=0; cnt=0; acnt=0; memset(son,0,sizeof(son)); } }trie[N]; int num; void insert(char *s) { int pos=0,len=strlen(s);
int fa=0; for(int i=0;i<len;++i) { pos=s[i]-a; if(!trie[fa].son[pos]){ trie[fa].son[pos]=++num; } fa=trie[fa].son[pos]; trie[fa].cnt++; } trie[fa].have=1; trie[fa].acnt++; } int find(char *s) { int len=strlen (s); int pos,fa=0; for(int i=0;i<len;++i) { pos=s[i]-a; if(!trie[fa].son[pos]){ return 0; } fa = trie[fa].son[pos]; } return trie[fa].cnt; } int main() { char word[20]; while(gets(word)) { int len=strlen(word); if(len==0)break; else insert(word); } while(gets(word)) { printf("%d\n",find(word)); } return 0; }

HDU 1251 統計難題