本文主要是介绍[HDU2222] Keywords Search AC自动机,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
关于last的理解 记录的是上一个和当前部分前缀相同的单词节点编号 用于快速查找
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<iostream>
#include<queue>
#define SF scanf
#define PF printf
#define max(a, b) ((a) < (b) ? (b) : (a))
using namespace std;
typedef long long LL;
const int MAXN = 10000;
const int MAXL = 10000 * 50;
const int SZ = 26;
char s[MAXL*2+10];
int ans;
struct Aho_Corasick
{int ch[MAXL+10][SZ], Ncnt, val[MAXL+10];int f[MAXL+10], last[MAXL+10];void init() { memset(ch[0], 0, sizeof(ch[0])); Ncnt = 1; memset(last, 0, sizeof(last)); }void New() {memset(ch[Ncnt], 0, sizeof(ch[Ncnt]));val[Ncnt] = 0;}inline int ID(char c) { return c - 'a'; }void insert(char *s, int pos){int u = 0, n = strlen(s);for(int i = 0; i < n; i++){int c = ID(s[i]);if(!ch[u][c]) {New();ch[u][c] = Ncnt++;}u = ch[u][c];}val[u]++;}void getFail(){queue <int> q;f[0] = 0;for(int c = 0; c < SZ; c++){int u = ch[0][c];if(u) { f[u] = 0; q.push(u); last[u] = 0; }}while(!q.empty()){int r = q.front(); q.pop();for(int c = 0; c < SZ; c++){int u = ch[r][c];if(!u) { ch[r][c] = ch[f[r]][c]; continue; }q.push(u);int v = f[r];while(v && !ch[v][c]) v = f[v];f[u] = ch[v][c];last[u] = val[f[u]] ? f[u] : last[f[u]];}}}void add(int j) {if(j) {ans += val[j]; val[j] = 0; add(last[j]);}}void solve(char *s) {int n = strlen(s), j = 0;for(int i = 0; i < n; i++){int c = ID(s[i]);j = ch[j][c];if(val[j]) add(j);else if(last[j]) add(last[j]);}}
}ac;
int main()
{int T; SF("%d", &T); while(T--) {int n; SF("%d", &n);ac.init(); ans = 0;for(int i = 1; i <= n; i++) {SF("%s", s);ac.insert(s, i);}ac.getFail();SF("%s", s);ac.solve(s);PF("%d\n", ans);}
}
/*
5
she
he
say
shr
her
yasherhs
*/
这篇关于[HDU2222] Keywords Search AC自动机的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!