模板_AC自动机
2017-09-09 13:05
225 查看
const int SIGMA_SIZE = 130; const int MAXNODE = 1000*55; const int MAXS = 150 + 10; struct ACautomata { int ch[MAXNODE][SIGMA_SIZE]; int f[MAXNODE]; // fail函数 int val[MAXNODE]; // 每个字符串的结尾结点都有一个非0的val int last[MAXNODE]; // 输出链表的下一个结点 //int cnt[MAXS]; int sz; void init() { sz = 1; memset(ch[0], 0, sizeof(ch[0])); // memset(cnt, 0, sizeof(cnt)); } // 字符c的编号 inline int idx(char c) { return c; } // 插入字符串。v必须非0 void insert(char *s, int v) { int u = 0, n = strlen(s); for(int i = 0; i < n; i++) { int c = idx(s[i]); if(!ch[u][c]) { memset(ch[sz], 0, sizeof(ch[sz])); val[sz] = 0; ch[u][c] = sz++; } u = ch[u][c]; } val[u] = v; } // 递归打印匹配文本串str[i]结尾的后缀,以结点j结尾的所有字符串 void print(int i,int j) { if(j) { //cnt[val[j]]++; vis[val[j]]++; print(i,last[j]); } } // 在T中找模板 int find(char* T) { int n = strlen(T); int j = 0; // 当前结点编号,初始为根结点 for(int i = 0; i < n; i++) { // 文本串当前指针 int c = idx(T[i]); j = ch[j][c]; if(val[j]) print(i,j); else if(last[j]) print(i,last[j]); // 找到了! } } // 计算fail函数 void getFail() { queue<int> q; f[0] = 0; // 初始化队列 for(int c = 0; c < SIGMA_SIZE; c++) { int u = ch[0][c]; if(u) { f[u] = 0; q.push(u); last[u] = 0; } } // 按BFS顺序计算fail while(!q.empty()) { int r = q.front(); q.pop(); for(int c = 0; c < SIGMA_SIZE; 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]]; } } } } ac;
相关文章推荐
- 关键词匹配(Ac自动机模板题)
- ac自动机模板
- HDU - 2222 Keywords Search(AC自动机模板 指针实现)
- AC自动机模板程序
- AC自动机模板——贴瓷砖
- hdu 3065 病毒侵袭持续中(ac自动机模板题)
- 关键词匹配(Ac自动机模板题)
- hihoCoder-1036 (AC自动机模板题)
- HDU 2222 Keywords Search (AC自动机模板题)
- HDU-2222-Keywords Search(AC自动机模板题)
- HDU 2222 Keywords Search (AC自动机模板题)
- HDU 2222 Keywords Search (AC自动机模板题)
- AC自动机模板 LA4670 Dominating Patterns 出现次数最多的字串 BNUOJ11552 UVA1449
- hdu 2222 Keywords Search (ac自动机模板题)
- hdu 2222 AC自动机静态模板
- HDU 2222 (AC自动机模板题)
- UVALive 4670 Dominating Patterns(AC自动机模板题)
- AC自动机模板
- HDU 2222 Keywords Search(AC自动机模板题)
- AC自动机模板->kuangbin