HDU1251 统计难题(Trie树)

来源:互联网 发布:windows 空间音效 编辑:程序博客网 时间:2024/06/13 09:28

Problem Description

Ignatius最近遇到一个难题,老师交给他很多单词(只有小写字母组成,不会有重复的单词出现),现在老师要他统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀).

Input

输入数据的第一部分是一张单词表,每行一个单词,单词的长度不超过10,它们代表的是老师交给Ignatius统计的单词,一个空行代表单词表的结束.第二部分是一连串的提问,每行一个提问,每个提问都是一个字符串.

注意:本题只有一组测试数据,处理到文件结束.

Output

对于每个提问,给出以该字符串为前缀的单词的数量.

Sample Input

bananabandbeeabsoluteacmbabbandabc

Sample Output

2310

思路

插入单词的时候每一个节点都记录一下就好

代码

#include <cstdio>#include <cstring>#include <string>#include <set>#include <cmath>#include <iostream>#include <stack>#include <queue>#include <vector>#include <algorithm>#define mem(a,b) memset(a,b,sizeof(a))#define inf 0x3f3f3f3f#define debug() puts("what the fuck!!!")#define ll long longusing namespace std;const int N=1000010+100;struct dicTree{    struct Node    {        int sum;        int next[26];    } Tree[N];    int root, sz;    int newnode()    {        for (int i = 0; i < 26; i++)            Tree[sz].next[i] = -1;        Tree[sz++].sum = 0;        return sz - 1;    }    void init()    {        sz = 0;        root = newnode();    }    void insert(string &s, int len)    {        int now = root;        for (int i = 0; i < len; i++)        {            int to = (int)(s[i] - 'a');            if (Tree[now].next[to] == -1)                Tree[now].next[to] = newnode();            now = Tree[now].next[to];            Tree[now].sum++;        }    }    int find(string &s, int len)    {        int now = root;        for (int i = 0; i < len; i++)        {            int to = (int)(s[i] - 'a');            if (Tree[now].next[to] == -1)                return 0;            now = Tree[now].next[to];        }        return Tree[now].sum;    }};dicTree dic;int main(){    ios::sync_with_stdio(false);    cin.tie(0);    int flag=1;    dic.init();    string s;    while(getline(cin,s))    {        if(s.size()==0)        {            flag=0;            continue;        }        if(flag)            dic.insert(s,s.length());        else            cout<<dic.find(s,s.length())<<endl;    }    return 0;}
原创粉丝点击