trie 树 模板

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#define maxn 2000010
using namespace std;
int tot, n, m, rt;
int trie[maxn][26], sum[400001];
char s[22];
//bool vis[maxn];查询整个单词用
void build()
{
    int len = strlen(s);
    rt = 0;
    for(int i=0; i<len; i++)
    {
        int x=s[i]-'a';
        if(trie[rt][x]==0)//现在插入的字母在之前同一节点处未出现过
        {
            trie[rt][x]=++tot;//字母插入一个新的位置,否则不做处理
        }
        //sum[trie[rt][x]]++;    前缀后移一个位置保存前缀出现的次数
        rt=trie[rt][x];//为下个字母的插入做准备
    }
    /*vis[rt]=true;标志该单词末位字母的尾结点,在查询整个单词时用到*/
}
bool qp()
{
    int len = strlen(s);
    rt = 0;
    for(int i=0; i<len; i++)
    {
        int x=s[i]-'a';
        if(trie[rt][x]==0)return false;//以rt为头结点的x字母不存在,返回0
        rt=trie[rt][x];//为查询下个字母做准备
    }
    return true;
    //查询整个单词时,应该return vis[rt] , 查询前缀出现的次数时,应该return sum[rt]
}
int main()
{
    tot=0;
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
    {
        cin>>s;
        build();
    }
    scanf("%d",&n);
    for(int i=1; i<=n; i++)
    {
        cin>>s;
        if(qp()) printf("YES\n");
        else printf("NO\n");
    }
    scanf("%d",&m);
    for(int i=1; i<=m; i++)
    {
        cin>> s;
        printf("%d",qp());

    }


    return 0;
}

 

 

    int idx(char s){
        if(s >= '0' && s <= '9'){
            return s - '0';
        }
 
        else if(s >= 'A' && s <= 'Z'){
            return 10 + s - 'A';
        }
 
        else{
            return 36 + s - 'a';
        }
 
    }

 

 

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
char s[11];
int n,m;
bool p;
struct node
{
    int count;
    node * next[26];
}*root;
node * build()
{
    node * k=new(node);
    k->count=0;
    memset(k->next,0,sizeof(k->next));
    return k;
}
void insert()
{
    node * r=root;
    char * word=s;
     while(*word)
    {
        int id=*word-'a';
        if(r->next[id]==NULL) r->next[id]=build();
        r=r->next[id];
        r->count++;
        word++;
    }
}
int search()
{
    node * r=root;
    char * word=s;
    while(*word)
    {
        int id=*word-'a';
        r=r->next[id];
        if(r==NULL) return 0;
        word++;
    }
    return r->count;
}
int main()
{
    root=build();
    scanf("%d",&n);
    for(int i=1;i<=n;i++) 
    {
            cin>>s;
            insert();
    }
    scanf("%d",&m);
    for(int i=1;i<=m;i++)
    {
        cin>>s;
        printf("%d\n",search());
    }
}

 

转载于:https://www.cnblogs.com/WTSRUVF/p/9261070.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值