hdu2846 Repository -字典树

Repository

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)



Problem Description
When you go shopping, you can search in repository for avalible merchandises by the computers and internet. First you give the search system a name about something, then the system responds with the results. Now you are given a lot merchandise names in repository and some queries, and required to simulate the process.
 

Input
There is only one case. First there is an integer P (1<=P<=10000)representing the number of the merchanidse names in the repository. The next P lines each contain a string (it's length isn't beyond 20,and all the letters are lowercase).Then there is an integer Q(1<=Q<=100000) representing the number of the queries. The next Q lines each contains a string(the same limitation as foregoing descriptions) as the searching condition.
 

Output
For each query, you just output the number of the merchandises, whose names contain the search string as their substrings.
 

Sample Input
  
  
20 ad ae af ag ah ai aj ak al ads add ade adf adg adh adi adj adk adl aes 5 b a d ad s
 

Sample Output
  
  
0 20 11 11 2
 

题目大意:
给你n个模板字符串,q个查询字符串,问每个查询字符串在模板字符串中出现了几次
解题思路
字典树,字典树是查前缀相同的,那么如果把模式串中的每个子串都放进字典树,那么再次查询的时候就相当于有以子串开头的了。例如
adc 将adc dc c 都存进字典树,那么查询以adc dc c都可行。
但是要注意有可能出现模板串的子串重复的情况例如
abab 将abab bab ab b 存进字典树,那么以ab为开头和以b为开头的都数了两次,不合法,所以再引入一个变量num, 存放这个字符是由第几个单词存进来的。


代码
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
char s1[20],s[20];

struct node
{
    int count;//这个字符出现过几次
    int num;//用来记录是哪个单词找的
    node *next[26];//它下面的26个英文字母
    node()
    {
        memset(next,NULL,sizeof(next));
        count = 0;
        num=0;
    }
};

node *p,*root=new node();

void insert(char *s ,int k)
{
    int i=0,t;
    p=root;//每次都要从根节点开始
    while(s[i]!='\0')//到这个单词结束
    {
        t=s[i]-'a';
        if(p->next[t]==NULL)
            p->next[t] =new node();
        p=p->next[t];
        if(p->num!=k)
            p->count++;
        p->num=k;
        i++;
    }
}

int find()
{
    int i=0,t;
    p=root;
    while(s[i]!='\0')
    {
        t=s[i]-'a';
        if(p->next[t]==NULL)
            return 0;
        else p=p->next[t];
        i++;
    }
    return p->count;
}

int main()
{
    int n;
    scanf("%d",&n);
    for(int i=1;i<=n;++i)
    {
        scanf("%s",s1);
        int j,len=strlen(s1);
        for(j=0;j<len;++j)
            insert(s1+j,i);
    }

    int q;
    scanf("%d",&q);
    while(q>0)
    {
        scanf("%s",s);
        int ans = find();
        printf("%d\n",ans);
        q--;
    }
    return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值