奥赛一本通 1482 单词
1482 单词
题目大意
一篇论文由许多单词组成,求每个单词分别在论文中出现多少次。
知识要点
AC 自动机
解题思路
在字典树上记录每个节点经过的次数,沿着 fail 指针传递即可得到每个单词被匹配的次数。
参考代码
#include <bits/stdc++.h>
using namespace std;
const int N = 1000005;
char s[N], t[N];
int cnt, trie[N][26], fail[N], Q[N];
int ans[N], pos[205];
int insert(char* s) {
int p = 0;
for(int i = 0; s[i]; i++) {
int c = s[i] - 'a';
if(!trie[p][c]) trie[p][c] = ++cnt;
p = trie[p][c], ans[p]++; //记录节点经过次数
}
return p;
}
void build() {
for(int l = 0, r = 1; l != r; l++) {
int f = Q[l], y = fail[f];
for(int c = 0; c < 26; c++) {
int x = trie[f][c];
if(x) Q[r++] = x, fail[x] = f ? trie[y][c] : 0;
else trie[f][c] = trie[y][c];
}
}
}
int main() {
int n;
scanf("%d", &n);
for(int i = 1; i <= n; i++) scanf("%s", s), pos[i] = insert(s);
build();
for(int i = cnt; i > 0; i--) ans[fail[Q[i]]] += ans[Q[i]]; //标记沿 fail 指针传递
for(int i = 1; i <= n; i++) printf("%d\n", ans[pos[i]]);
return 0;
}

浙公网安备 33010602011771号