hdu-2846-Repository(字典树)


题意:给你一些字符串,然后会有一些询问,然后输出  询问的字符串 在 给出的字符串中出现多少次(在前缀,后缀,中间出现都算)但要注意 例如  adada   询问  ad  只能算是一次;

思路:用字典树存  adada  存成  adada dada ada da a 存5个单词 但是要做上标记  (标记成一个单词)

这里还要说一点要用C++提交不能用G++否者会超内存;

code:

#include<cstdio>
#include<cstring>
#include<stdlib.h>
using namespace std;
struct node
{
    int cut;
    int k;///标记是否为一个单词
    node *next[26];
    node(){
        cut=0;
        k=0;
        for(int i=0;i<26;i++){
            next[i]=NULL;
        }
    }
};
node *root;
void Insert(char *str,int a)
{
    node *p=root;
    int len = strlen(str);
    for(int i=0;i<len;i++){
        int id=str[i]-'a';
        if(p->next[id]==NULL)
            p->next[id]=new node;
        p=p->next[id];
        if(p->k!=a){///当为一个单词时不用再让cut++了;
            p->cut++;
            p->k=a;
        }
    }
}
int Find(char *str)
{
    node *p=root;
    int len=strlen(str);
    for(int i=0;i<len;i++){
        int id = str[i]-'a';
        if(p->next[id]!=NULL){
            p=p->next[id];
        }
        else return 0;
    }
    return p->cut;
}
int main()
{
    root=new node;
    int t,n;
    char str[25],ss[25];
    scanf("%d",&t);
    for(int k=1;k<=t;k++){
        scanf("%s",str);
        int len=strlen(str);
        for(int i=0;i<len;i++){
            strncpy(ss,str+i,len-i);///截取一段长度的字符串  copy 给另一个字符串
            ss[len-i]='\0';
            Insert(ss,k);
        }
    }
    scanf("%d",&n);
    while(n--){
        scanf("%s",&str);
        printf("%d\n",Find(str));
    }
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值