AcWing 142:前缀统计 ← 字典树(Trie树)之前缀统计

【题目来源】
https://www.acwing.com/problem/content/144/

【题目描述】
给定 N 个字符串 S1,S2…SN,接下来进行 M 次询问,每次询问给定一个字符串 T,求 S1∼SN 中有多少个字符串是 T 的前缀。
输入字符串的总长度不超过 10^6,
仅包含小写字母

【输入格式】
第一行输入两个整数 N,M。
接下来 N 行每行输入一个字符串 Si。
接下来 M 行每行一个字符串 T 用以询问。

【输出格式】
对于每个询问,输出一个整数表示答案。
每个答案占一行。

【数据范围】
1≤N,M≤10^5

【输入样例】
3 2
ab
bc
abc
abc
efg

【输出样例】
2
0

【算法分析】
● 关于字典树的介绍,请详见:

https://blog.csdn.net/hnjzsyjyj/article/details/138599488
https://blog.csdn.net/hnjzsyjyj/article/details/138631374
● 在本题代码的 query() 函数中,虽有 p=sn[p][u]; 语句,但发现使用 if(p==0) return ans;  能得出正确结果,但使用 if(sn[p][u]==0) return ans; 无法得出正确结果。从逻辑上看,没有问题。难道是 C++ 有什么未关注到的细节?请广大朋友指正。

【算法代码】

#include <bits/stdc++.h>
using namespace std;

const int maxn=1e6+5;
int sn[maxn][26]; //sn[p][u] indicates the serial number
int cnt[maxn]; //number of words ending in the current node
string str;
int idx;

void insert(string s) {
    int p=0; //root=0
    for(int i=0; i<s.size(); i++) {
        int u=s[i]-'a'; //a~z are mapped to 0~25
        if(!sn[p][u]) sn[p][u]=++idx;
        p=sn[p][u];
    }
    cnt[p]++;
}

int query(string s) {
    int ans=0;
    int p=0; //root=0
    for(int i=0; i<s.size(); i++) {
        int u=s[i]-'a'; //a~z are mapped to 0~25
        p=sn[p][u];
        if(p==0) return ans;
        ans+=cnt[p];
    }
    return ans;
}

int main() {
    int n,m;
    cin>>n>>m;
    for(int i=1; i<=n; i++) cin>>str, insert(str);
    for(int i=1; i<=m; i++) cin>>str, cout<<query(str)<<endl;

    return 0;
}

/*
in:
3 2
ab
bc
abc
abc
efg

out:
2
0
*/




【参考文献】
https://oi-wiki.org/string/trie/
https://blog.csdn.net/hnjzsyjyj/article/details/138599488
https://blog.csdn.net/hnjzsyjyj/article/details/138631374
https://www.acwing.com/solution/content/85508/


 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值