HDU 1251 統計難題【字典樹】
阿新 • • 發佈:2019-02-06
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 131070/65535 K (Java/Others)
Total Submission(s): 46494 Accepted Submission(s): 16531
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
字典樹的基礎應用。
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
using namespace std;
#define ll long long int
struct Trie {
int v;
Trie *next[26];
};
Trie root;
void createTrie(char *str)
{
int len = strlen(str);
Trie *p = &root, *q;
for (int i = 0; i < len; i++)
{
int id = str[i] - 'a';
if (p->next[id] == NULL)
{
q = (Trie *)malloc(sizeof(root));
q->v = 1;
for (int j = 0; j < 26; j++)
{
q->next[j] = NULL;
}
p->next[id] = q;
p = p->next[id];
}
else
{
p->next[id]->v++;
p = p->next[id];
}
}
}
int findTrie(char *str)
{
int len = strlen(str);
Trie *p = &root;
for (int i = 0; i < len; i++)
{
int id = str[i] - 'a';
p = p->next[id];
if (p == NULL)
return 0;//chaxunwuguo
}
return p->v;
}
int main()
{
char str[15];
int i;
for (i = 0; i < 26; i++)
{
root.next[i] = NULL;
}
while (gets(str)&&str[0]!='\0')
{
createTrie(str);
}
memset(str, 0, sizeof str);
while (~scanf("%s", str))
{
int ans = findTrie(str);
printf("%d\n", ans);
}
return 0;
}