字典树

字典树与KMP模板

字典树与KMP PPT课件


1.数组保存

#include <stdio.h>
#include <string.h>
const int maxn=10000;//提前估计好可能会开的节点的个数

int tot;            //节点编号,模拟申请新节点,静态申请
int trie[maxn][26]; //假设每个节点的分支有26个
bool isw[maxn];     //判断该节点是不是单词结尾

void insert(char *s,int rt){
    for(int i=0;s[i];i++){
        int x=s[i]-'a';//假设单词都是小写字母组成
        if(trie[rt][x]==0){//没有,申请新节点
            trie[rt][x]=++tot;
        }
        rt=trie[rt][x];
    }
    isw[rt]=true;
}

bool find(char *s,int rt){
    for(int i=0;s[i];i++){
        int x=s[i]-'a';//假设单词都是小写字母组成
        if(trie[rt][x]==0){
            return false;
        }
        rt=trie[rt][x];
    }
    return isw[rt];
}

char s[22];//单词读入

int main(){
    tot=0;//一开始没有节点

    int rt=++tot;//申请一个根节点
    memset(trie[rt],0,sizeof(trie[rt]));//初始化根节点
    memset(isw,false,sizeof(isw));

    while(scanf("%s",s),s[0]!='#'){//新建字典,以一个'#'结束
        insert(s,rt);
    }
    while(scanf("%s",s),s[0]!='#'){//查单词,以一个'#'结束
        if(find(s,rt))
            printf("%s 在字典中\n",s);
        else
            printf("%s 不在字典中\n",s);
    }
    return 0;
}


2.动态指针

///hdu1251
#include<stdio.h>
#include<string.h>
struct trie{
    int cnt;
    trie *next[26];
};
trie *root=new trie;
void insert(char ch[]){
    trie *p=root,*newnode;
    for(int i=0;ch[i]!='\0';i++){
        if(p->next[ch[i]-'a']==0){
            newnode=new trie;
            for(int j=0;j!=26;j++){
                newnode->next[j]=NULL;
            }
            newnode->cnt=1;
            p->next[ch[i]-'a']=newnode;
            p=newnode;
        }else{
            p=p->next[ch[i]-'a'];
            p->cnt++;
        }
    }
}
int find(char ch[]){
    trie *p=root;
    for(int i=0;ch[i]!='\0';i++){
        if(p->next[ch[i]-'a']!=NULL)
            p=p->next[ch[i]-'a'];
        else
            return 0;
    }
    return p->cnt;
}
int main(){
    char ch[20];
    for(int i=0;i!=26;i++){
        root->next[i]=NULL;
    }
    root->cnt=0;
    while(gets(ch)){//必须用gets
        if(!strcmp(ch,"")) break;
        insert(ch);
    }
    while(scanf("%s",ch)!=EOF){
        printf("%d\n",find(ch));
    }
    return 0;
}




字典树KMP优先队列完整学习课件打包:点击下载课件压缩包

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值