hdu1251(字典树)

题意:给一本字典,求给定字符串有多少个前缀
字典树入门题

#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;
}
/*
banana
banda
band
bee
absolute
acm

ba
b
band
abc
*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值