Trie树 hiho一下第2周

本文详细介绍了Trie树的数据结构实现及其应用。通过C++代码实现了Trie树的基本操作,包括插入字符串和查找字符串出现次数的功能。适用于初学者了解Trie树的工作原理。

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

**题意:**trie树的实现题。

思路:实现 trie 树就好。

代码:

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<stack>
#include<queue>
#include<utility>
#include<vector>
#include<cmath>
#include<set>
#include<map>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long LL;

const int sigma_size = 30;
const int maxnode = 1000010;

int ch[maxnode][sigma_size];
int val[maxnode];
int cnt[maxnode];
int sz;
int N, M;

void Init()
{
    sz = 1;
    memset(ch[0], 0, sizeof(ch[0]));
    memset(cnt, 0, sizeof(cnt));
}

int idx(char c)
{
    return c-'a';
}

void Insert(char *s)
{
    int u = 0, n = strlen(s);
    for(int i=0; i<n; i++){
        int c = idx(s[i]);
        if(!ch[u][c]){
            memset(ch[sz], 0, sizeof(ch[sz]));
            val[sz] = 0;
            ch[u][c] = sz++;
        }
        u = ch[u][c];
        cnt[u]++;
    }
    val[u] = 1;
}

int Find(char *s)
{
    int u = 0, n = strlen(s);
    for(int i=0; i<n; i++){
        int c = idx(s[i]);
        if(!ch[u][c]){
            return 0;
        }
        u = ch[u][c];
    }
    return cnt[u];
}

int main()
{
    //freopen("in.txt", "r", stdin);
    Init();
    scanf("%d", &N);
    char c[15];
    for(int i=0; i<N; i++){
        scanf("%s", c);
        Insert(c);
    }

    scanf("%d", &M);
    for(int i=0; i<M; i++){
        scanf("%s", c);
        int ans = Find(c);
        printf("%d\n", ans);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值