关闭

hdu2846 Repository -字典树

标签: 字典树代码
116人阅读 评论(0) 收藏 举报
分类:

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

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:32075次
    • 积分:2252
    • 等级:
    • 排名:第16686名
    • 原创:184篇
    • 转载:1篇
    • 译文:0篇
    • 评论:10条
    最新评论