hdu 2846 经典字典树

思路:因为字典树只能读取前缀有多少个相同的, 对于求子串可以将字符串分成
多个字串看成单独的字符串 进行建 字典树,但要注意这两个字符串 abab, ab
他们的字串都有 ab a 所以在建树时 判断是否同一个字符串 不同就加 1 ;

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

struct Trie
{
    int num;
    int tot;//记录梅个字串对应的原字符串的序号
    Trie *next[26];
    Trie()
    {
        num = tot = 0;
        memset(next, 0, sizeof(next));
    }
}root;

void createTrie(char *str, int x)
{
    int len = strlen(str);
    Trie *p = &root, *q;
    for(int i = 0; i < len; i++)
    {
        int id = str[i] - 'a';
        if(p->next[id] == NULL)
        {
            q = new Trie;
            p->next[id] = q;
        }
        p = p->next[id];
        if(p->tot != x) p->num++;
        p->tot = x;
    }
}

int findTrie(char *str)
{
    int len = strlen(str);
    Trie *p = &root;
    for(int i = 0; i < len; i++)
    {
        int id = str[i] - 'a';
        p = p->next[id];
        if(p == NULL) return 0;
    }
    return p->num;
}

int main()
{
    int n;
    char str[26];
    while(cin >> n)
    {
        for(int i = 1; i <= n; i++)
        {
            cin >> str;
            int len = strlen(str);
            for(int j = 0; j < len; j++) createTrie(str+j, i);
        }
        cin >> n;
        for(int i = 0; i < n; i++)
        {
            cin >> str;
            cout << findTrie(str) << endl;
        }
    }
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值