hihocoder1014(字典树)

来源:互联网 发布:mac如何登陆两个微信 编辑:程序博客网 时间:2024/05/21 15:07

题目连接:点击打开链接


解题思路:

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


完整代码:

#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++;        else            p->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];        else            return 0;        i++;    }    return p->cnt; //返回最后的那个字符  所在节点的 nCount}int main(){    #ifdef DoubleQ    freopen("in.txt","r",stdin);    #endif    while(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;}



0 0