HDU 2846 Repository

本文介绍了一道关于字典树变形的算法题目,并提供了一份详细的C++代码实现。通过对输入字符串进行处理并构建字典树,实现了字符串匹配计数的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:

http://acm.hdu.edu.cn/showproblem.php?pid=2846

题解:

字典树变形(注意要交C++,不然会爆内存。。。。。。)

代码:

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
#define met(a,b) memset(a,b,sizeof(a))
#define inf 0x3f3f3f3f;
const int maxn = 27;
struct Tire
{
    Tire *next[maxn];
    int cnt;
    int id;
    Tire(){
        cnt=0;
        id=-1;
        for(int i=0;i<maxn;i++)
            next[i]=NULL;
    }
}root;
int n,m;

void create(char *s,int ID)
{
    int k = 0;
    Tire *p = &root;
    while(s[k]!='\0')
    {
        int pos=s[k]-'a';
        if(p->next[pos]==NULL)
            p->next[pos]=new Tire;
        p=p->next[pos];
        if(p->id!=ID)
            p->cnt++;
        p->id=ID;
        k++;
    }
}

int search(char *s)
{
    int k = 0;
    Tire *p = &root;
    while(s[k]!='\0'&&p->next[s[k]-'a'])p=p->next[s[k++]-'a'];
    return s[k]=='\0'?p->cnt:0;
}

int main()
{
    char s[35];
    scanf("%d",&n);
    for(int i=0;i<n;i++)
    {
        scanf("%s",s);
        int len=strlen(s);
        for(int j=0;j<len;j++)
            create(s+j,i);
    }
    scanf("%d",&m);
    while(m--)
    {
        scanf("%s",s);
        printf("%d\n",search(s));
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值