字典树

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
using namespace std;
const int N=2*1e5+10;
int n,m,q,k,j;
struct Dictree//字典树
{
    int cont;//单词出现次数
    struct Dictree  *tree[26];//26个子节点
}*a;//a为头结点是空的
void init()
{
    a=new Dictree;
    for(int i=0; i<26; ++i)  //子节点置空
    {
        a->tree[i]=NULL;
    }
}
void Insert(string str)//建树
{
    int len,j;
    Dictree *head=a;//head是头指针
    len=str.size();
    for(int i=0; i<len; ++i)
    {
        j=(int)(str[i]-'a');
        if(head->tree[j]==NULL)//如果没有这个字母
        {
            head->tree[j]=new Dictree;
            head=head->tree[j];
            head->cont=1;//该节点值初始化
            for(int k=0; k<26; k++)//子节点置空
                head->tree[k]=NULL;
        }
        else
        {
            head=head->tree[j];
            head->cont++;
        }
    }
}
int Find(string str)
{
    int len=str.size();
    Dictree *head=a;
    for(int i=0; i<len; i++)//找字符串是否在树中出现过
    {
        j=(int)(str[i]-'a');
        if(head->tree[j]!=NULL)
            head=head->tree[j];
        else//如果该字符没有则说明树中没有该字符串
            return 0;
    }
    return head->cont;//找到后返回有多少个
}
int main()
{
    init();
    int n;
    while(~scanf("%d",&n))
    {
        string str;
        for(int i=0; i<n; i++)
        {
            cin>>str;
            Insert(str);
        }
        int m;
        cin>>m;
        for(int i=0; i<m; i++)
        {
            cin>>str;
            int sum=Find(str);
            printf("%d\n",sum);
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值