Description
Ignatius最近遇到一個難題,老師交給他很多單詞(只有小寫字母組成,不會有重複的單詞出現),現在老師要他統計出以某個字符串爲前綴的單詞數量(單詞本身也是自己的前綴).
Input
輸入數據的第一部分是一張單詞表,每行一個單詞,單詞的長度不超過10,它們代表的是老師交給Ignatius統計的單詞,一個空行代表單詞表的結束.第二部分是一連串的提問,每行一個提問,每個提問都是一個字符串.
注意:本題只有一組測試數據,處理到文件結束.
Output
對於每個提問,給出以該字符串爲前綴的單詞的數量.
Sample Input
banana
band
bee
absolute
acm
ba
b
band
abc
Sample Output
2
3
1
0
題解:用字典樹就好啦,如果數據量很大的話需要加dfs釋放new出來的內存哦^_^
#include<cstdio>
#include<cmath>
#include<cstring>
#include<iostream>
#include<algorithm>
#define Tcases int T;scanf("%d",&T);while(T--)
using namespace std;
char words[15], mode[15];
struct node {
int val;
node* next[26];
node() {
for (int i = 0; i < 26; i++)
next[i] = NULL;
val = 0;
}
}root;
void build_Trie(char str[]) {
int len = strlen(str);
node * p = &root;
for (int i = 0; i < len; i++) {
int c = str[i] - 'a';
if (p->next[c] == NULL) {
p->next[c] = new node();
}
p = p->next[c];
(p->val)++;
}
}
int find_Trie(char str[]) {
int len = strlen(str);
node* p = &root;
for (int i = 0; i < len; i++) {
int c = str[i] - 'a';
p = p->next[c];
if (p == NULL)
return 0;
}
return p->val;
}
int main()
{
#ifdef _DEBUG
freopen("debug.in", "r", stdin);
#define gets(buff) gets_s(buff)
#endif
while (gets(words) != NULL&&words[0] != '\0'&&words[0] != ' ') {
build_Trie(words);
}
while (gets(mode) != NULL) {
printf("%d\n", find_Trie(mode));
}
return 0;
}