HDU1251 统计难题【字典树】

题目链接:

?pid=1251

题目大意:

给你一张单词表,每个单词占一行,以空行结束。再给你几个单词前缀。那么问题来了:

统计出单词表中以所给单词前缀为前缀的单词数目。

思路:

其实就是字典树的模板应用。根据所给单词表建立一个字典树,,并记录所有前缀的个数。

然后根据所给单词前缀去字典树中查找是否含有这个前缀。找到就输出该前缀的个数。

AC代码:

#include<iostream>#include<algorithm>#include<cstdio>#include<cstring>using namespace std;struct TrieNode{int Count;struct TrieNode* Next[26];}Tree,*Trie;TrieNode *root;void Create(){root = new TrieNode;memset(root->Next,NULL,sizeof(root->Next));root->Count = 0;}void Insert(char *s){TrieNode *p, *q;p = root;while(*s){if(p->Next[*s-'a'] == NULL){q = new TrieNode;memset(q->Next,NULL,sizeof(q->Next));q->Count = 1;p->Next[*s-'a'] = q;}elsep->Next[*s-'a']->Count++;p = p->Next[*s-'a'];s++;}}int Find(char *s){TrieNode *p, *q;p = root;while(*s){if(p->Next[*s-'a'] == NULL)return 0;p = p->Next[*s-'a'];s++;}return p->Count;}int main(){char s[27];Create();while(gets(s) && s[0]!=0){Insert(s);}while(cin >> s){cout << Find(s) << endl;}return 0;}

接受失败等于回归真实的自我,接受失败等于打破完美的面具,

HDU1251 统计难题【字典树】

相关文章:

你感兴趣的文章:

标签云: