hihocoder1014(字典树)

题目连接:点击打开链接

解题思路:

字典树模板题。论一套靠谱模板的重要性!!!

完整代码:

#include <algorithm>#include <iostream>#include <cstring>#include <complex>#include <cstdio>#include <string>#include <cmath>#include <queue>using namespace std;typedef unsigned long long LL;const int MOD = int(1e9)+7;const int INF = 0x3f3f3f3f;const double EPS = 1e-9;const double PI = acos(-1.0); //M_PI;const int maxn = 2000001;int n , m;char ss[maxn];#define MAX 26typedef struct node{int cnt; // 该节点前缀 出现的次数struct node *next[MAX]; //该节点的后续节点} trie;trie mem[maxn]; //先分配好内存。 malloc 较为费时int allocp = 0;//初始化一个节点。nCount计数为1,, next都为nulltrie *creat(){trie * p = &mem[allocp++];p->cnt = 1;for(int i = 0 ; i < MAX ; i ++)p->next[i] = NULL;return p;}void insert(trie **pRoot, char *str){trie *p = *pRoot;int i = 0, k;//一个一个的插入字符while (str[i]){k = str[i] – 'a'; //当前字符 应该插入的位置if (p->next[k])p->next[k]->cnt++;elsep->next[k] = creat();p = p->next[k];i++; //移到下一个字符}}int find(trie *root, char *str){if (root == NULL)return 0;trie *p = root;int i = 0, k;while (str[i]){k = str[i] – 'a';if (p->next[k])p = p->next[k];elsereturn 0;i++;}return p->cnt; //返回最后的那个字符 所在节点的 nCount}int main(){#ifdef DoubleQfreopen("in.txt","r",stdin);#endifwhile(cin >> n){trie *Root = creat();for(int i = 0 ; i < n ; i ++){cin >> ss;insert(&Root , ss);}cin >> m;for(int i = 0 ; i < m ; i ++){cin >> ss;cout << find(Root , ss) << endl;}}return 0;}

离开睁眼闭眼看见的城市,逃离身边的纷纷扰扰,

hihocoder1014(字典树)

相关文章:

你感兴趣的文章:

标签云: