字典树模板

该代码实现了一个基于C++的数据结构,用于字符串处理,具有O(n)的时间复杂度进行查询和插入操作。通过一个自定义的Node结构体,程序维护了一个字符串的字典树(Trie),并提供了insert和match两个函数,分别用于添加字符串到树中和查找匹配的字符串计数。
摘要由CSDN通过智能技术生成

https://www.luogu.com.cn/problem/P8306

这个数据结构的查询和插入都是O(n)的时间复杂度

代码:

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<memory.h>
#include<map>
#include<vector>
#include<list>
#include<string>
#include<cmath>
#include<queue>
#include<sstream>
#include<iterator>
using namespace std;
typedef  long long ll;
typedef pair<ll, ll> Pii;
const int N = 3e6 + 5;
int tot = 0;
char s[N];
int getNum(char c)
{
    if (c>='0'&&c<='9')
    {
        return c - '0' + 52;
    }
    else
    {
        if (c >= 'a' && c <= 'z')
        {
            return c - 'a';
        }
        else
        {
            return c - 'A' + 26;
        }
    }
}
struct Node
{
    int nx[70] = {0};
    int cnt=0;
}tr[N];
void insert(char target[])
{
    int root = 0;
    int len = strlen(target);
    for (int i = 0; i < len; i++)
    {
        int t = getNum(target[i]);
        tr[root].cnt++;
        if (!tr[root].nx[t])
        {
            tr[root].nx[t] = ++tot;
        }
        root = tr[root].nx[t];

    }
    tr[root].cnt++;
}
int match(char target[])
{
    int root = 0;
    int len = strlen(target);
    for (int i = 0; i < len; i++)
    {
        int t = getNum(target[i]);

        if (!tr[root].nx[t])
        {
            return 0;
        }

        root = tr[root].nx[t];

        if (i == len - 1)
        {
            return tr[root].cnt;
        }

    }
}
int main() {

    //freopen("in.txt", "r", stdin);
    ios::sync_with_stdio(0);
    cin.tie(0);
    int t;
    cin >> t;
    while (t--)
    {
        int n, m;
        cin >> n >> m;
        for (int i = 0; i <= tot; i++)
        {
            tr[i].cnt = 0;
            for (int j = 0; j < 70; j++)
            {
                tr[i].nx[j] = 0;
            }
        }
        tot = 0;
        for (int i = 1; i <= n; i++)
        {
            
            cin >> s;
            insert(s);
        }
        for (int i = 1; i <= m; i++)
        {
            cin >> s;
            cout << match(s)<<"\n";
        }
    }
    

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值