[HDU2222] Keywords Search && AC自动机

来源:互联网 发布:淘宝定制怎么弄 编辑:程序博客网 时间:2024/05/17 23:58

关于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);}}/*5shehesayshrheryasherhs */


0 0