您的位置:首页 > 其它

zoj -- 3228 Searching the String(AC自动机)

2014-08-14 11:42 253 查看
给出一个字符串。有n个询问,0 string表示string在字符串中出现多少次,可以重叠。1 string表示string在字符串中出现多少次,string不能重叠。

http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3228

维护一个last数组,记录该字符串上次出现的位置,根据这个来判断有没有重叠。

//#pragma comment(linker,"/STACK:1024000000,1024000000")
#include <map>
#include <set>
#include <cmath>
#include <queue>
#include <stack>
#include <cstdio>
#include <string>
#include <vector>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;

typedef double DB;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> PII;

#define pb push_back
#define MP make_pair
#define lson l, m, rt << 1
#define rson m + 1, r, rt << 1 | 1

const double eps = 1e-6;
const int inf = 0x3f3f3f3f;
const int mod = 100000;
const int maxn = 600000 + 10;

char str[100010], ss[100];
int n, op[100010], pos[100010], cas = 0;
int tot[maxn][2], last[maxn];
int d[maxn];

const int max_chd = 26;///字母表大小
struct AC_automata{
int chd[maxn][max_chd], fail[maxn], cnt[maxn];///trie中的chd数组,fail指针,节点标记(是多少个串的结尾)
int root, sz;///根节点,trie树大小
int newnode(){///建立新的节点,返回节点编号
for(int i=0; i<max_chd; i++) chd[sz][i] = -1;
d[sz] = 0;
cnt[sz++] = 0;
return sz - 1;
}
void init(){
sz = 0;
root = newnode();
}
int ID(char ch){
return ch - 'a';
}
int Insert(char * str){///建trie树
int cur = root;
int len = strlen(str);
for(int i=0; i<len; i++){
if(chd[cur][ID(str[i])] == -1)
chd[cur][ID(str[i])] = newnode(), d[chd[cur][ID(str[i])]] = i + 1;
cur = chd[cur][ID(str[i])];
}
cnt[cur]++;
return cur;
}
void build(){///构建fail指针
queue<int> Q;
while(!Q.empty()) Q.pop();
fail[root] = root;
for(int i=0; i<max_chd; i++){
if(chd[root][i] == -1)
chd[root][i] = root;
else{
fail[chd[root][i]] = root;
Q.push(chd[root][i]);
}
}
while(!Q.empty()){
int now = Q.front(); Q.pop();
for(int i=0; i<max_chd; i++){
if(chd[now][i] == -1)
chd[now][i] = chd[fail[now]][i];
else {
fail[chd[now][i]] = chd[fail[now]][i];
Q.push(chd[now][i]);
}
}
}
}
void Query(char * str){
memset(tot, 0, sizeof(tot));
memset(last, -1, sizeof(last));
int now = root;
int len = strlen(str);
for(int i=0; i<len; i++){
now = chd[now][ID(str[i])];
int tmp = now;
while(tmp != root){
if(cnt[tmp]){
tot[tmp][0]++;
if(i - last[tmp] >= d[tmp]) tot[tmp][1]++, last[tmp] = i;
}
tmp = fail[tmp];
}
}
for(int i=0; i<n; i++){
printf("%d\n", tot[pos[i]][op[i]]);
}
}
}AC;

int main(){
while(scanf("%s", str) == 1){
scanf("%d", &n);
AC.init();
for(int i=0; i<n; i++){
scanf("%d%s", &op[i], ss);
pos[i] = AC.Insert(ss);
}
AC.build();
printf("Case %d\n", ++cas);
AC.Query(str);
puts("");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  AC自动机 字符串