简单字典树 模板

本文介绍了一种使用Trie树进行字符串匹配的方法,并通过一个具体的C++代码示例展示了如何构建Trie树来存储一系列字符串,进而进行高效查询。该方法首先构建Trie树,然后遍历树以统计特定条件下的节点数量。

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

#include<bits/stdc++.h>
using namespace std;
const int N = 2000000+10;
struct node{
    node *next[26];
    int num;
    bool ok;
    node() {
        for(int i=0;i<26;i++) {
            next[i] = NULL;
        }
        num = 0, ok = 0;
    }
};
int n;
char s[N];
node *root;
int ans = 0;
void dfs(node *rt) {
    if(rt == NULL) return ;
    if(rt->num <= 5) {
        ans++;
        return ;
    }
    for(int i=0;i<26;i++) {
        dfs(rt->next[i]);
    }
}

void ins(char *s) {
    int len = strlen(s);
    node * rt = root;
    for(int i=0;i<len; i++) {
        int id = s[i] - 'a';
        if(rt->next[id] == NULL) {
            rt->next[id] = new node();
        }
        rt = rt->next[id];
        rt->num++;
    }
    rt->ok = true;
}

void del(node *rt) {
    if(rt == NULL) return ;
    for(int i=0;i<26;i++) {
        if(rt->next[i] != NULL) del(rt->next[i]);
    }
    delete p;
}

int main () {
    int T; scanf("%d",&T);
    while (T--) {
        ans = 0;
        scanf("%d",&n);
        root = new node();
        for(int i=0;i<n;i++)
            scanf("%s",s) , ins(s);
        for(int i=0;i<26;i++) {
            if(root->next[i]!=NULL)
                dfs(root->next[i]);
        }
        cout << ans<<endl;
    }
    return 0;
}

 

转载于:https://www.cnblogs.com/Draymonder/p/9496600.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值