前缀统计 字典树模板
链接:https://ac.nowcoder.com/acm/contest/1010/A
来源:牛客网
题目描述
给定N个字符串S1,S2…SNS_1,S_2 \dots S_NS1,S2…SN,接下来进行M次询问,每次询问给定一个字符串T,求S1∼SNS_1 \sim S_NS1∼SN中有多少个字符串是T的前缀。输入字符串的总长度不超过10610^6106,仅包含小写字母。
输入描述:
第一行两个整数N,M。接下来N行每行一个字符串Si。接下来M行每行一个字符串表示询问。
输出描述:
对于每个询问,输出一个整数表示答案
示例1
输入
复制
3 2
ab
bc
abc
abc
efg
输出
复制
2
0
模板题
#define debug
#ifdef debug
#include <time.h>
#include "/home/majiao/mb.h"
#endif
#include <iostream>
#include <algorithm>
#include <vector>
#include <string.h>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <math.h>
#define MAXN ((int)1e5+7)
#define ll long long int
#define INF (0x7f7f7f7f)
#define fori(lef, rig) for(int i=lef; i<=rig; i++)
#define forj(lef, rig) for(int j=lef; j<=rig; j++)
#define fork(lef, rig) for(int k=lef; k<=rig; k++)
#define QAQ (0)
using namespace std;
#define show(x...) \ do { \ cout << "\033[31;1m " << #x << " -> "; \ err(x); \ } while (0)
void err() { cout << "\033[39;0m" << endl; }
template<typename T, typename... A>
void err(T a, A... x) { cout << a << ' '; err(x...); }
namespace FastIO{
char print_f[105];
void read() {}
void print() { putchar('\n'); }
template <typename T, typename... T2>
inline void read(T &x, T2 &... oth) {
x = 0;
char ch = getchar();
ll f = 1;
while (!isdigit(ch)) {
if (ch == '-') f *= -1;
ch = getchar();
}
while (isdigit(ch)) {
x = x * 10 + ch - 48;
ch = getchar();
}
x *= f;
read(oth...);
}
template <typename T, typename... T2>
inline void print(T x, T2... oth) {
ll p3=-1;
if(x<0) putchar('-'), x=-x;
do{
print_f[++p3] = x%10 + 48;
} while(x/=10);
while(p3>=0) putchar(print_f[p3--]);
putchar(' ');
print(oth...);
}
} // namespace FastIO
using FastIO::print;
using FastIO::read;
int n, m, Q, K;
char buf[MAXN];
#define ch (s[i]-'a')
struct Node {
int cnt;
Node* next[26];
Node() : cnt(0) { memset(next, false, sizeof(next)); }
} *root = new Node();
void insert(char* s) {
Node* now = root;
for(int i=0; s[i]; i++) {
if(!now->next[ch]) now->next[ch] = new Node();
now = now->next[ch];
}
now->cnt ++;
}
int query(char* s) {
Node* now = root;
int ans = 0;
for(int i=0; s[i]; i++) {
if(!now->next[ch]) return ans;
now = now->next[ch];
ans += now->cnt;
}
return ans;
}
int main() {
#ifdef debug
freopen("test", "r", stdin);
clock_t stime = clock();
#endif
scanf("%d %d ", &n, &m);
for(int i=1; i<=n; i++) {
scanf("%s ", buf);
insert(buf);
}
while(m--) {
scanf("%s ", buf);
printf("%d\n", query(buf));
}
#ifdef debug
clock_t etime = clock();
printf("rum time: %lf 秒\n",(double) (etime-stime)/CLOCKS_PER_SEC);
#endif
return 0;
}