hihoCoder #1014 : Trie树

来源:互联网 发布:it项目经验 知乎 编辑:程序博客网 时间:2024/05/15 00:25

题目分析

统计以某字符串为前缀的单词的数量,首先建立字典树,注意字典树的点数为100000,同时是由小写字母都成的,我们用val作为标记数组,每当有单词从这个位置走过那么我们就加一,那么val表示的意思就是以该前缀的单词的数量,遍历一下找到最后一个点就可以了,详细请看代码。

#include <cstdio>#include <cstring>#include <iostream>#include <algorithm>using namespace std;const int maxnode = 1000005;const int sigma_size = 27;struct Trie{    int ch[maxnode][sigma_size];    int val[maxnode];    int sz;    Trie() {sz = 1; memset(ch[0], 0, sizeof(ch[0]));}    int idx(char c) {return c - 'a';}    void Insert(char *s)    {        int u = 0,n = strlen(s);        for(int i = 0; i < n; i++)        {            int c = idx(s[i]);            if(!ch[u][c])            {                memset(ch[sz], 0, sizeof(ch[sz]));                val[sz] = 1;                ch[u][c] = sz++;                u = ch[u][c];            }            else            {                u = ch[u][c];                val[u]++;            }        }    }    int Inquire(char *s)    {        int u = 0,n = strlen(s);        for(int i = 0; i < n; i++)        {            int c = idx(s[i]);            if(!ch[u][c])                return 0;            else                u = ch[u][c];        }        return val[u];    }};Trie trie;int main(){    int n,m;    char str[15];    scanf("%d", &n);    while(n--)    {        scanf("%s", str);        trie.Insert(str);    }    scanf("%d", &m);    while(m--)    {        scanf("%s", str);        printf("%d\n", trie.Inquire(str));    }    return 0;}
0 0
原创粉丝点击