[HDU2222] Keywords Search && AC自动机
2015-01-13 23:07
387 查看
关于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自动机)
- hdu2222 Keywords Search (AC自动机)
- hdu2222 Keywords Search(ac自动机)
- HDU2222:Keywords Search(AC自动机)
- 【HDU2222】Keywords Search(AC自动机)
- HDU2222 Keywords Search(AC自动机模板题)
- [HDU2222]Keywords Search(AC自动机)
- HDU2222[Keywords Search] AC自动机裸题
- [hdu2222]Keywords Search(AC自动机)
- [HDU2222]Keywords Search(AC自动机)
- HDU2222 Keywords Search(AC自动机)
- HDU2222 Keywords Search (字符串处理-ac自动机)
- hdu2222-- Keywords Search(AC自动机入门1)
- [HDU2222]Keywords Search(AC自动机)
- 【HDU2222】Keywords Search(AC自动机)
- AC自动机——HDU2222(题号很鬼畜)Keywords Search
- hdu_2222: Keywords Search(AC自动机模板题)
- HDU 2222 Keywords Search(AC自动机)
- hdu2222 Keywords Search(AC自动机模板题)
- hdu 2222 Keywords Search(AC自动机)