洛谷字典树板子题目


注意点1:初始化无论用memset还是vector<n,0>的时间复杂度都是o(n),会超时,

要高效利用已知资源,利用上一次的idx初始化。

P8306 【模板】字典树 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)

#include <bits/stdc++.h>

using namespace std;
typedef long long ll;
typedef double db;
typedef long double ldb;
typedef pair<int, int> pii;
typedef pair<ll, ll> PII;
#define pb emplace_back
//#define int ll
#define all(a) a.begin(),a.end()
#define x first
#define y second
#define ps push_back
#define endl '\n'
#define IOS ios::sync_with_stdio(0),cin.tie(0),cout.tie(0)
#define ve1 vector<ll>
#define ve2 vector<vector<ll>>
void solve();
const int N = 3e6 + 5;

signed main() {
    IOS;
    ll t;
    cin >> t;
    while(t--)
        solve();
    return 0;
}

ll idx,ch[N][10+26*2],cnt[N];
// idx 节点编号,根节点是0
// ch 存储字典树的数组
// cnt 字典树的模版是用来统计单词个数的,这里用来统计前缀个数

void init()//初始化参数
{
    for(int i = 0; i <= idx; ++ i)//上一次只用到了最大到idx
    {
        for(int j = 0; j < 10 + 26 * 2; ++ j)
            ch[i][j] = 0;
        cnt[i] = 0;//将每个节点的前缀数量归零
    }
    idx = 0;//别忘了这个,记录节点编号的东西
}
void insert(string s)//建立字典树
{
    int p = 0;//根结点是0
    for(auto it : s)
    {
        ll j;
        if(it >= '0' && it <= '9') j = it - '0';
        else if(it < 'a') j = it - 'A' + 10;
        else j = it - 'a' + 26 + 10;//A从26开始
        // 上面三行是映射字符,将字符变为数字好处理
        if(!ch[p][j]) ch[p][j] = ++ idx;//没有找到
        p = ch[p][j];
        cnt[p] ++;
    }

}

ll query(string s)//查询函数
{
    int p = 0;
    for(auto it : s)
    {
        ll j;
        if(it >= '0' && it <= '9') j = it - '0';//数字
        else if(it < 'a') j = it - 'A' + 10;//A从10开始
        else j = it - 'a' + 26 + 10;//小写字母
        if(!ch[p][j]) return 0;//字节点的编号不是0,如果是0则没有这条边
        p = ch[p][j];
    }
    return cnt[p];
}



void solve() {
    init();//初始化
    ll n ,q;
    cin >> n >> q;
    for(int i = 1; i <= n; ++ i)
    {
        string s; cin >> s;
        insert(s);
    }
    for(int i = 1; i <= q; ++ i)
    {
        string s; cin >> s;
        cout << query(s) << endl;
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值