通过这题改正了以前一个重复模板匹配很低效的地方,见注释
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <queue>
#include <algorithm>
#include <vector>
#include <cstring>
#include <stack>
#include <cctype>
#include <utility>
#include <map>
#include <string>
#include <climits>
#include <set>
#include <string>
#include <sstream>
#include <utility>
#include <ctime>
using std::priority_queue;
using std::vector;
using std::swap;
using std::stack;
using std::sort;
using std::max;
using std::min;
using std::pair;
using std::map;
using std::string;
using std::cin;
using std::cout;
using std::set;
using std::queue;
using std::string;
using std::istringstream;
using std::make_pair;
using std::getline;
using std::greater;
using std::endl;
using std::multimap;
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int, int> PAIR;
typedef multimap<int, int> MMAP;
const int MAXN(600010);
const int SIGMA_SIZE(26);
const int MAXM(110);
const int MAXE(4000010);
const int MAXH(18);
const int INFI((INT_MAX-1) >> 2);
const int BASE(131);
const int MOD(20090717);
const ULL LIM(1000000000000000ull);
char str[100010];
int point[100010], type[100010]; //每个询问串所指向的节点,每个询问的类型
int pos[MAXN];
int at[2][MAXN];
struct Q
{
int ind, next;
};
struct AC
{
int ch[MAXN][SIGMA_SIZE];
int val[MAXN], f[MAXN], last[MAXN];
int size;
void init()
{
memset(ch[0], 0, sizeof(ch[0]));
f[0] = val[0] = last[0] = 0;
at[0][0] = at[1][0] = 0;
pos[0] = -1;
size = 1;
}
inline int idx(char temp)
{
return temp-'a';
}
void insert(char *S, int tv, int len)
{
int u = 0, id;
for(; *S; ++S)
{
id = idx(*S);
if(!ch[u][id])
{
memset(ch[size], 0, sizeof(ch[size]));
val[size] = 0;
at[0][size] = at[1][size] = 0;
pos[size] = -1;
ch[u][id] = size++;
}
u = ch[u][id];
}
val[u] = len;
point[tv] = u; //处理重复模板时一定不要用vector或者链式存储每个询问
//而是每个询问建立一个指针指向该节点
}
int que[MAXN];
int front, back;
void construct()
{
front = back = 0;
int cur, u;
for(int i = 0; i < SIGMA_SIZE; ++i)
{
u = ch[0][i];
if(u)
{
que[back++] = u;
f[u] = last[u] = 0;
}
}
while(front < back)
{
cur = que[front++];
for(int i = 0; i < SIGMA_SIZE; ++i)
{
u = ch[cur][i];
if(u)
{
que[back++] = u;
f[u] = ch[f[cur]][i];
last[u] = val[f[u]]? f[u]: last[f[u]];
}
else
ch[cur][i] = ch[f[cur]][i];
}
}
}
void find(char *T)
{
int u = 0, id, ti = 0;
for(; *T; ++T, ++ti)
{
id = idx(*T);
u = ch[u][id];
for(int pi = u; pi; pi = last[pi])
{
//如果采用vector或链式解决重复模板的话,当重复的串较多时
//效率将会受很大影响,采用询问指针来解决则没有这个问题
//因为采用指针解决,重复模板对AC自动机来说是透明的,自动机认为只有一个模板串
//而指针可以解释该节点属于哪个模板串
++at[0][pi];
if(ti-pos[pi] >= val[pi])
{
++at[1][pi];
pos[pi] = ti;
}
}
}
}
};
AC ac;
void solve(int n)
{
ac.find(str);
for(int i = 1; i <= n; ++i)
printf("%d\n", at[type[i]][point[i]]);
printf("\n");
}
int main()
{
char tstr[10];
int n_case(0);
while(~scanf("%s", str))
{
int n;
scanf("%d", &n);
ac.init();
for(int i = 1; i <= n; ++i)
{
scanf("%d%s", type+i, tstr);
ac.insert(tstr, i, strlen(tstr));
}
ac.construct();
printf("Case %d\n", ++n_case);
solve(n);
}
return 0;
}