题意:给出一个长字符串S和一组询问字符串,对于每个询问需要知道在S中是否存在两个位置不同的子串可以组成该询问字符串。
建S的后缀自动机,同时处理出每个状态出现的最左位置和最右的位置。拿每一个询问和S的自动机匹配,记录下询问串中以每个位置为结尾所匹配的长度和匹配自动机中哪个状态。设l为整个询问串所能匹配的长度,那么我们检测这样的结尾i(len - l =< i < len)是否可以匹配整个前缀,同时所匹配的状态所出现的最左的位置满足要求。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define lng long long
using namespace std;
const int maxn = 200000 + 10;
int pos[2000], length[2000];
char str[maxn];
struct suffixautomaton
{
int ch[maxn][30], pre[maxn], val[maxn];
int top[maxn], c[maxn], l[maxn], r[maxn];
int sz, last;
void init() { pre[0] = -1; last = 0; sz = 1; memset(ch[0], 0, sizeof(ch[0])); }
void insert(int x)
{
int p = last, np = sz++; last = np;
memset(ch[np], 0, sizeof(ch[np]));
val[np] = val[p] + 1;
while(p != -1 && ch[p][x] == 0)
{
ch[p][x] = np;
p = pre[p];
}
if(p == -1) pre[np] = 0;
else
{
int q = ch[p][x];
if(val[q] == val[p] + 1)
pre[np] = q;
else
{
int nq = sz++;
memcpy(ch[nq], ch[q], sizeof(ch[q]));
val[nq] = val[p] + 1;
pre[nq] = pre[q];
pre[q] = pre[np] = nq;
while(p != -1 && ch[p][x] == q) { ch[p][x] = nq; p = pre[p]; }
}
}
}
void calc()
{
int len = strlen(str);
memset(c, 0, sizeof(c));
for(int i = 0; i < sz; ++i) c[val[i]] += 1;
for(int i = 1; i <= len; ++i) c[i] += c[i - 1];
for(int i = 0; i < sz; ++i) top[--c[val[i]]] = i;
for(int i = 0; i < sz; ++i) { l[i] = len + 1; r[i] = 0; }
for(int i = 0; ; i = ch[i][str[val[i]] - 'A'])
{
l[i] = r[i] = val[i];
if(val[i] == len) break;
}
for(int i = sz - 1; i > 0; --i)
{
int u = top[i];
l[pre[u]] = min(l[pre[u]], l[u]);
r[pre[u]] = max(r[pre[u]], r[u]);
}
}
int query(char * s)
{
int len = strlen(s);
if(len == 1) return 0;
int ll = 0, u = 0;
for(int i = 0; i < len; ++i)
{
int x = s[i] - 'A';
if(ch[u][x])
{
u = ch[u][x];
ll++;
}
else
{
while(pre[u] != -1 && ch[u][x] == 0) u = pre[u];
if(ch[u][x]) { ll = val[u]; u = ch[u][x]; ll++; }
else u = 0, ll = 0;
}
pos[i] = u; length[i] = ll;
}
u = pos[len - 1];
if(length[len - 1] == len) return 1;
while(u != 0)
{
for(int i = len - min(val[u], length[len - 1]) - 1; i < len - val[pre[u]]; ++i)
if(length[i] == i + 1 && l[pos[i]] <= r[u] - (len - i - 1)) return 1;
u = pre[u];
}
return 0;
}
}sam;
int n;
int main()
{
freopen("in.txt", "r", stdin);
scanf("%s %d", str, &n);
sam.init();
for(int i = 0; str[i]; ++i) sam.insert(str[i] - 'A');
sam.calc();
int res = 0;
for(int i = 0; i < n; ++i)
{
char tmp[2000];
scanf("%s", tmp);
int tmpr = sam.query(tmp);
res += tmpr;
}
cout << res << "\n";
return 0;
}