奥赛一本通 1476 Secret Message 秘密信息
1476 Secret Message 秘密信息
题目大意
给定 $n$ 个字符串 $s_1, s_2, \dots, s_n$,多次询问另一个字符串 $t$,计算有多少个 $s_i$ 满足 $s_i$ 是 $t$ 的前缀或 $t$ 是 $s_i$ 的前缀。
知识要点
字典树
解题思路
在字典树上插入字符串时,累计每个节点的经过次数,它统计了有多少个字符串以当前节点为前缀。同时字符串 $t$ 在字典树上匹配时,记录它经过了多少个字符串的结尾,也就是这些字符串都是它的前缀。
参考代码
#include <bits/stdc++.h>
using namespace std;
const int N = 500005;
int cnt, trie[N][2], num[N], siz[N];
void insert() {
int k, c, p = 0;
scanf("%d", &k);
while(k--) {
scanf("%d", &c);
if(!trie[p][c]) trie[p][c] = ++cnt;
p = trie[p][c], siz[p]++;
}
num[p]++;
}
int query() {
int k, c, p = 0, ans = 0;
scanf("%d", &k);
while(k--) {
scanf("%d", &c);
ans += num[p], p = trie[p][c]; //累计经过的单词末尾
if(!p) break;
}
while(k-- > 0) scanf("%d", &c); //多余的输入
return ans + siz[p];
}
int main() {
int n, m;
scanf("%d%d", &n, &m);
while(n--) insert();
while(m--) printf("%d\n", query());
return 0;
}

浙公网安备 33010602011771号