Codeforces 235C
题目:给定一主串(S),(n)次询问,每次询问串(t)的所有循环移位串的出现的次数和
做法:建(SAM),对于询问串(t),将他复制一份放在后边,在后缀自动机上匹配,如果匹配长度大于(|t|),就沿着(fa), 找到第一次大于(|t|)的位置,用这个状态的(right)数组更新答案。注意到可能会匹配到重复的状态,所以要对会更新答案的状态去重。
#include <bits/stdc++.h>
typedef long long ll;
const int N = 1000010 << 1;
using namespace std;
struct SAM{
int n, step[N], fa[N], ch[N][26], right[N], num[N], last, root, cnt;
char s[N>>1];
SAM(){last = root = ++cnt; }
void add(int x){
int tmp = s[x] - 'a', p = last, np = ++cnt;
step[last = np] = x, right[np] = 1;
while(p && !ch[p][tmp]) ch[p][tmp] = np, p = fa[p];
if(!p) fa[np] = root;
else{
int q = ch[p][tmp];
if(step[q] == step[p] + 1) fa[np] = q;
else{
int nq = ++cnt; step[nq] = step[p] + 1;
memcpy(ch[nq], ch[q], sizeof(ch[q]));
fa[nq] = fa[q], fa[q] = fa[np] = nq;
while(ch[p][tmp] == q) ch[p][tmp] = nq, p = fa[p];
}
}
}
int tmp[N];
void calright(){
memset(tmp, 0, sizeof(tmp));
for(int i = 1; i <= cnt; i++) tmp[step[i]]++;
for(int i = 1; i <= n; i++) tmp[i] += tmp[i - 1];
for(int i = cnt; i; i--) num[tmp[step[i]]--] = i;
for(int i = cnt; i; i--) right[fa[num[i]]] += right[num[i]];
}
void run(){
scanf(" %s",s+1), n = strlen(s + 1);
for(int i = 1; i <= n; i++) add(i);
calright();
}
char str[N];
int len;
set<int> S;
ll solve() {
scanf(" %s",str+1), len = strlen(str+1);
for(int i = 1; i <= len; ++i) str[i+len] = str[i];
int now = root, tmp = 0; ll ans = 0;
for(int i = 1; i <= len+len; ++i) {
int x = str[i]-'a';
if(ch[now][x]) now = ch[now][x], ++tmp;
else {
while(now && !ch[now][x]) now = fa[now];
if(!now) now = root, tmp = 0;
else tmp = step[now]+1, now = ch[now][x];
}
while(now!=1 && step[fa[now]] >= len) now = fa[now], tmp = step[now];
if(tmp >= len) S.insert(now);
}
for(set<int>::iterator it = S.begin(); it != S.end(); ++it) ans += right[*it];
S.clear();
return ans;
}
} Fe;
int main() {
Fe.run();
int q;
scanf("%d",&q);
while(q--) {
printf("%I64d
",Fe.solve());
}
}