标签:ac自动机
ac自动机代码
#include <cstdio>
#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
#define id(a) (a-‘a‘)
const int maxnode=10000*50+10;
int ch[maxnode][26];
int f[maxnode];
int val[maxnode];
int sz;
int insert(char *s){
int u = 0;
for(int i = 0;s[i];i++){
int c = id(s[i]);
if(!ch[u][c]){
memset(ch[sz],0,sizeof(ch[sz]));
val[sz] = 0;
f[sz] = 0;
ch[u][c] = sz++;
}
u = ch[u][c];
}
val[u] ++;
}
int find_fail(){
int u = 0;
queue<int> que;
f[0]= 0;
for(int i = 0;i < 26;i++){
int u = ch[0][i];
if(u){
f[u] = 0;
que.push(u);
}
}
while(!que.empty()){
int r = que.front();
que.pop();
for(int i = 0;i < 26;i++){
if(!ch[r][i]){
ch[r][i] = ch[f[r]][i];
}
else{
f[ch[r][i]] = ch[f[r]][i];
que.push(ch[r][i]);
}
}
}
}
int query(char *s){
int u = 0;
int ans = 0;
for(int i = 0;s[i];i++){
u = ch[u][id(s[i])];
int tmp = u;
while(tmp){
ans += val[tmp] ;
val[tmp] = 0;
tmp = f[tmp];
}
}
printf("%d\n",ans);
return ans;
}
char s[1000005];
char a[100];
int main(){
int t;
cin >> t;
while(t--){
int n;
cin >> n;
sz = 1;
memset(ch[0],0,sizeof(ch[0]));
val[0]= 0;
f[0] =0;
for(int i = 0;i < n;i++){
scanf("%s",a);
insert(a);
}
find_fail();
scanf("%s",s);
query(s);
}
}
裸trie代码
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <queue>
#include <cmath>
#include <cstring>
#include <stack>
#include <set>
#include <map>
#include <vector>
using namespace std;
#define INF 0x2fffffff
#define LL long long
#define MAX(a,b) ((a)>(b))?(a):(b)
#define MIN(a,b) ((a)<(b))?(a):(b)
#define id(a) ((a)-‘a‘)
const int maxnode = 10000*50+10;
int ch[maxnode][26];
int val[maxnode];
int sz = 0;
int insert(char *s){
int len =strlen(s);
int u = 0;
for(int i = 0;i < len;i++){
int c = id(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] ++;
}
int query(char *s){
int ans = 0;
for(int i = 0;s[i];i++){
int c = id(s[i]);
int u = 0;
int j = 0;
while(ch[u][c]){
if(val[ch[u][c]]){
ans += val[ch[u][c]];
val[ch[u][c]] = 0;
}
u = ch[u][c];
j ++;
c = id(s[i+j]);
}
}
printf("%d\n",ans);
}
char s[1000005];
int main(){
int t;
freopen("1.txt","r",stdin);
freopen("2.txt","w",stdout);
scanf("%d",&t);
while(t--){
int n;
scanf("%d",&n);
char a[100];
memset(ch[0],0,sizeof(ch[0]));
val[0]= 0;
sz = 1;
for(int i = 0;i < n;i++){
scanf("%s",a);
insert(a);
}
scanf("%s",s);
query(s);
}
return 0;
}
裸字典树的时候只要了600多ms,写ac自动机却用了700多ms,而且开始的时候不知道哪里错了,一直wa,tle,re,mle,这哪里是ac自动机啊,分明是wa自动机,tle自动机,re自动机,mle自动机啊 !
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:ac自动机
原文地址:http://blog.csdn.net/qq_24667639/article/details/47262851