您的位置:首页 > 其它

HDU 2222 AC自动机

2016-08-26 20:45 204 查看
板子:和LRJ的板子几乎一样。。略加修改了一点点一点我喜欢的变量方式而已

/*
* AC自动机,令g[i,j]表示从i到j这一路遍历的所有字符串。 f[i]的意义就是g[?,i]和g[0,f[i]]的字符串是相等的
* last[i] ,表示g[0,last[i]]的字符串,是确定存在的,并且以last[i]结尾的字符串*/

struct AhoCorasickAutomata {
int ch[MAXNODE][SIGMA_SIZE];
int f[MAXNODE];    // fail函数
int val[MAXNODE];  // 每个字符串的结尾结点都有一个非0的val
int last[MAXNODE]; // 输出链表的下一个结点
int cnt[MAXNODE];
int sz;
queue<int>q;

void init() {
sz = 1;
memset(ch[0], 0, sizeof(ch[0]));
memset(cnt, 0, sizeof(cnt));
ms.clear();
}

// 字符c的编号
int idx(char c) {
return c-'a';
}

// 插入字符串。v必须非0
void insert(char s[], int len, int v) {
int now = 0;
for(int i = 0; i < len; i++) {
int c = idx(s[i]);
if(!ch[now][c]) {
memset(ch[sz], 0, sizeof(ch[sz]));
val[sz] = 0;
ch[now][c] = sz++;
}
now = ch[now][c];
}
val[now] ++;//单词出现次数
//ms[string(s)] = v;
}

// 递归打印以结点j结尾的所有字符串
void print(int j) {
if(j) {
//cnt[val[j]]++;
cnt[j]=1;
print(last[j]);
}
}

// 在T中找模板,text串的下标从0开始,长度为len
int find(char text[], int len) {
int j = 0; // 当前结点编号,初始为根结点
for(int i = 0; i < len; i++) { // 文本串当前指针
int c = idx(text[i]);
while(j && !ch[j][c]) j = f[j]; // 顺着细边走,直到可以匹配
j = ch[j][c];
if(val[j]) 	print(j);
else if(last[j]) print(last[j]); // 找到了!
}
}

//计算fail指针
void get_fail()
{
f[0] = 0;//fail[i]表示,当匹配到某个位置失败,下一个自动的位置
for (int c = 0; c < SIGMA_SIZE; c++)
{
int will = ch[0][c];
if (will)
{
f[will]=0;
q.push(will);
last[will] = 0;
}
}
while (!q.empty())
{
int now = q.front();
q.pop();
for (int c = 0; c < SIGMA_SIZE; ++ c)
{
int will = ch[now][c];	//now节点,想要访问的下标
if (!will)	continue;//如果这个下标不存在,直接continue;
q.push(will);
int pre = f[now];	//失配指针,先指now的失配,至少有一段都是相等的
while (pre && !ch[pre][c])	pre = f[pre];//往前跳失配指针,类似 KMP
f[will] = ch[pre][c];	//f为成功指针,指向应该的方向
last[will] = val[f[will]] ? f[will] : last[f[will]];
}
}
}

void doit()
{

/*
* 调试ac自动机数组信息用的
for (int i = 0; i < sz; ++ i)
{
prln(i);
for (int j = 0; j < 26;++j)
{
if (ch[i][j])	cout<< ((char)(j+'a'))<<" "<<ch[i][j]<<endl;;
}
//cout<<endl;
//cout<<endl;
}

for (int i = 0; i < sz; ++ i)
{
pr(i),prln(val[i]);
}

for (int i = 0; i < sz; ++ i)
{
pr(i),prln(f[i]);
}

for (int i = 0; i < sz; ++ i)
{
pr(i),prln(last[i]);
}
*/

int ans = 0;
for (int i = 0; i != sz; ++ i)
{
ans += val[i] * cnt[i];
}
cout<<ans<<endl;
}
}ac;


ac code:

#include<cstring>
#include <iostream>
#include<queue>
#include<cstdio>
#include<map>
#include<string>
using namespace std;

const int SIGMA_SIZE = 26;
const int MAXNODE = 500000 * 3;
#define prln(x) cout<<#x<<" = "<<x<<endl
#define pr(x) cout<<#x<<" = "<<x<<" "

map<string,int> ms;

/* * AC自动机,令g[i,j]表示从i到j这一路遍历的所有字符串。 f[i]的意义就是g[?,i]和g[0,f[i]]的字符串是相等的 * last[i] ,表示g[0,last[i]]的字符串,是确定存在的,并且以last[i]结尾的字符串*/ struct AhoCorasickAutomata { int ch[MAXNODE][SIGMA_SIZE]; int f[MAXNODE]; // fail函数 int val[MAXNODE]; // 每个字符串的结尾结点都有一个非0的val int last[MAXNODE]; // 输出链表的下一个结点 int cnt[MAXNODE]; int sz; queue<int>q; void init() { sz = 1; memset(ch[0], 0, sizeof(ch[0])); memset(cnt, 0, sizeof(cnt)); ms.clear(); } // 字符c的编号 int idx(char c) { return c-'a'; } // 插入字符串。v必须非0 void insert(char s[], int len, int v) { int now = 0; for(int i = 0; i < len; i++) { int c = idx(s[i]); if(!ch[now][c]) { memset(ch[sz], 0, sizeof(ch[sz])); val[sz] = 0; ch[now][c] = sz++; } now = ch[now][c]; } val[now] ++;//单词出现次数 //ms[string(s)] = v; } // 递归打印以结点j结尾的所有字符串 void print(int j) { if(j) { //cnt[val[j]]++; cnt[j]=1; print(last[j]); } } // 在T中找模板,text串的下标从0开始,长度为len int find(char text[], int len) { int j = 0; // 当前结点编号,初始为根结点 for(int i = 0; i < len; i++) { // 文本串当前指针 int c = idx(text[i]); while(j && !ch[j][c]) j = f[j]; // 顺着细边走,直到可以匹配 j = ch[j][c]; if(val[j]) print(j); else if(last[j]) print(last[j]); // 找到了! } } //计算fail指针 void get_fail() { f[0] = 0;//fail[i]表示,当匹配到某个位置失败,下一个自动的位置 for (int c = 0; c < SIGMA_SIZE; c++) { int will = ch[0][c]; if (will) { f[will]=0; q.push(will); last[will] = 0; } } while (!q.empty()) { int now = q.front(); q.pop(); for (int c = 0; c < SIGMA_SIZE; ++ c) { int will = ch[now][c]; //now节点,想要访问的下标 if (!will) continue;//如果这个下标不存在,直接continue; q.push(will); int pre = f[now]; //失配指针,先指now的失配,至少有一段都是相等的 while (pre && !ch[pre][c]) pre = f[pre];//往前跳失配指针,类似 KMP f[will] = ch[pre][c]; //f为成功指针,指向应该的方向 last[will] = val[f[will]] ? f[will] : last[f[will]]; } } } void doit() { /* * 调试ac自动机数组信息用的 for (int i = 0; i < sz; ++ i) { prln(i); for (int j = 0; j < 26;++j) { if (ch[i][j]) cout<< ((char)(j+'a'))<<" "<<ch[i][j]<<endl;; } //cout<<endl; //cout<<endl; } for (int i = 0; i < sz; ++ i) { pr(i),prln(val[i]); } for (int i = 0; i < sz; ++ i) { pr(i),prln(f[i]); } for (int i = 0; i < sz; ++ i) { pr(i),prln(last[i]); } */ int ans = 0; for (int i = 0; i != sz; ++ i) { ans += val[i] * cnt[i]; } cout<<ans<<endl; } }ac;

char text[1000031];
char tmp[100];
int n;

int main() {
int T;
scanf("%d", &T);

while (T--)
{
ac.init();
scanf("%d", &n);
for(int i = 1; i <= n; i++) {
scanf("%s", tmp);
ac.insert(tmp, strlen(tmp), i);
}
//ac.get_fail();
ac.get_fail();
scanf("%s", text);
ac.find(text, strlen(text));
ac.doit();
}
return 0;
}


节约内存版AC自动机(慢一倍)

#include <bits/stdc++.h>
#include <ext/pb_ds/priority_queue.hpp>
#include <tr1/unordered_map>
using std::tr1::unordered_map;
//using std::setiosflags;
//using std::setprecision;
using std::sort;
using std::max;
using std::min;
using std::cout;
using std::stack;
using std::cin;
using std::endl;
using std::swap;
using std::pair;
using std::vector;
using std::set;
using std::map;
using std::make_pair;
using std::multiset;
using std::unique;
using std::queue;
using std::greater;
using std::string;
using std::priority_queue;
using std::lower_bound;//返回第一个不小于
using std::upper_bound;//返回第一个大于
using std::max_element;
using std::min_element;
using __gnu_pbds::pairing_heap_tag;
#define x first
#define y second
#define mp make_pair
#define Hash unordered_map
#define clr(x) memset(x,0,sizeof(x))
#define logz(x) (31-__builtin_clz((int)x))
#define logzl(x) (63-__builtin_clzll((LL)x))
#define cf std::ios::sync_with_stdio(0);std::cin.tie(0)
typedef unsigned long long uLL;
typedef long long LL;
typedef pair<int, int> pii;
typedef pair<double, double> pdd;
typedef __gnu_pbds::priority_queue<pii, greater<pii>, pairing_heap_tag> Heap;//小根堆
typedef Heap::point_iterator Hit;
const Hit null;
const double PI = acos(-1);
const LL LINF = 0x3f3f3f3f3f3f3f3fll;//4e18
const int INF = 0x3f3f3f3f;//1e9
const double eps = 1e-8;
const int MOD = 1e9 + 7;

#define pr(x) cout<<#x<<" = "<<x<<" "
#define prln(x) cout<<#x<<" = "<<x<<endl
char patt[1000010];
char s[1000010];
int vis[1000010];
int n;

const int MAXNODE = 1000010;
int ans = 0;

struct AhoCorasickAutomata {
int head[MAXNODE]; // head[i]为第i个结点的左儿子编号
int next[MAXNODE]; // next[i]为第i个结点的右兄弟编号
char ch[MAXNODE]; // ch[i]为第i个结点上的字符
//int tot[MAXNODE]; // tot[i]为第i个结点为根的子树包含的叶结点总数
int val[MAXNODE];
int last[MAXNODE];
int f[MAXNODE]; //fail指针
int sz; // 结点总数
int cnt[MAXNODE];
queue<int>q;

void init()
{
// 初始时只有一个根结点
sz = 1;
//tot[0] = 0;
head[0] = next[0] = 0;
memset(val, 0, sizeof(val));
memset(last, 0, sizeof(last));
memset(f, 0, sizeof(f));
memset(cnt,0,sizeof(cnt));
}

// 插入字符串s,沿途更新tot
void insert(char s[], int len) {
int now = 0, will;
//tot[0]++;
for(int i = 0; i < len; i++) {
// 找字符s[i]
bool found = false;
for(will = head[now]; will; will = next[will])
if(ch[will] == s[i]) // 找到了
{
found = true;
break;
}
if(!found)
{
will = sz++; // 新建结点
//tot[will] = 0;
ch[will] = s[i];
next[will] = head[now];
head[now] = will; // 插入到链表的首部
head[will] = 0;
}
now = will;
//tot[now]++;
}
val[now] ++ ;
}

int is_son(int now, char t)//查找now节点,的t字符,有则返回下标,否则返回0(root)
{
//ch是否是now的儿子
for (int will = head[now]; will; will = next[will])
{
if (ch[will]==t) return will;
}
return 0;
}

void get_fail()
{
f[0] = 0;//fail[i]表示,当匹配到某个位置失败,下一个自动的位置
for (int now = head[0]; now; now = next[now])
{
f[now]=0;
q.push(now);
last[now] = 0;
}
while (!q.empty())
{
int now = q.front();
q.pop();
for (int will = head[now]; will; will = next[will])
{
q.push(will);
int pre = f[now]; //失配指针,先指now的失配,至少有一段都是相等的
while (pre && !is_son(pre,ch[will])) pre = f[pre];//往前跳失配指针,类似 KMP
f[will] = is_son(pre, ch[will]); // f[i]的意义就是g[?,i]和g[0,f[i]]的字符串是相等的
last[will] = val[f[will]] ? f[will] : last[f[will]];
}
}
}

// 递归打印以结点j结尾的所有字符串
void print(int j) //输出j节点的信息,如果last[j]存在,last[j]的位置也有字符
{
if(j)
{
//vis[pos] = max(val[j], vis[pos]);
cnt[j]=1;
print(last[j]);
}
}

int idx(char ch)
{
if ('a' <= ch && ch <='z') return ch;
if ('A' <= ch && ch <='Z') return ch -'A'+'a';
return ch;
}

// 在T中找模板,text串的下标从0开始,长度为len
void find(char text[], int len) {
int j = 0; // 当前结点编号,初始为根结点
for(int i = 0; i < len; i++) { // 文本串当前指针
char c = text[i];
while (j && !is_son(j, c)) j = f[j];
j = is_son(j, c);
if(val[j]) print(j);
else if(last[j]) print(last[j]); // 找到了!
}
int ans=0;
for (int i = 0;i<=sz; ++i)
ans += cnt[i]*val[i];
cout<<ans<<endl;
}
}ac;

void init()
{
scanf("%d ", &n);
ac.init();
for (int i = 1; i <=n;++i)
{
gets(s);
ac.insert(s, strlen(s));
}
ac.get_fail();
gets(patt);
ac.find(patt, strlen(patt));
}

int main()
{
int T;
scanf("%d",&T);
while (T--)
{
init();
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: