hdu1251(字典树)

来源:互联网 发布:计算机编程语言分类 编辑:程序博客网 时间:2024/05/21 09:14
题意:给一本字典,求给定字符串有多少个前缀
字典树入门题
#include<iostream>#include<algorithm>#include<cstring>#include<stack>#include<queue>#include<set>#include<map>#include<stdio.h>#include<stdlib.h>#include<ctype.h>#include<time.h>#include<math.h>#define inf 0x7fffffff#define eps 1e-9#define N 1000000//注意数组要开大些#define pi acos(-1.0)#define P system("pause")using namespace std;char str[100];int res;struct trie{    int ch[N][30];    int val[N];    int sz ;    trie()    {        sz = 1;        memset(ch[0],0,sizeof(ch[0]));    }    void insert()    {        int u = 0, len = strlen(str);        int i;        for(i = 0; i < len; i++)        {            int c = str[i] - 'a';            if(!ch[u][c])            {                memset(ch[sz],0,sizeof(ch[sz]));                val[sz] = 0;                ch[u][c] = sz++;            }            u = ch[u][c];        }        val[u] = 1;    }    void query()    {        int u = 0, len = strlen(str);        int i;        for(i = 0 ; i < len; i++)        {            int c = str[i] - 'a';            if(!ch[u][c]) return;            u = ch[u][c];        }        if(val[u] == 1) res++;        count(u);    }    void count(int u)    {        int i;        for(i = 0 ; i < 26; i++)        {                if(ch[u][i])                {                        if(val[ch[u][i]] == 1)  res++;                        count(ch[u][i]);                }        }    }};trie tree;int main(){//freopen("input.txt","r",stdin);//freopen("output.txt","w",stdout);    while(cin.getline(str,100))    {        int len = strlen(str);        if(len == 0) break;        tree.insert();    }    while(scanf("%s",str) != EOF)    {        res = 0;        tree.query();        printf("%d\n",res);    }    return 0;}/*bananabandabandbeeabsoluteacmbabbandabc*/

0 0
原创粉丝点击