Description
\(t\) 组询问。每组询问给出一个字符串 \(S\) 。要求求出一个 \(num\) 数组一一对于字符串 \(S\) 的前 \(i\) 个字符构成的子串,既是它的后缀同时又是它的前缀,并且该后缀与该前缀不重叠,将这种字符串的数量记作 \(num_i\) 。输出 \(\prod\limits_{i=1}^{lenth(S)}(num_i+1)\) 。
\(1\leq t\leq 5,1\leq lenth(S)\leq 1000000\)
Solution
显然可以用两个指针来操作。一个还是求 \(KMP\) 的 \(next\) 数组的指针;令一个则是递推出 \(num\) 数组的指针。
首先注意到的是第二个指针的含义是满足题意的长度最长的前缀(后缀)的长度。其实递推 \(next\) 数组时,可以预处理出一个辅助数组 \(cnt_i\) ,表示前 \(i\) 个字符构成的子串,既是它的后缀同时又是它的前缀的个数。显然 \(num_i\) 为第二个指针位置的 \(cnt\) 的值。 \(O(n)\) 递推即可。
Code
//It is made by Awson on 2018.3.14#include#define LL long long#define dob complex #define Abs(a) ((a) < 0 ? (-(a)) : (a))#define Max(a, b) ((a) > (b) ? (a) : (b))#define Min(a, b) ((a) < (b) ? (a) : (b))#define Swap(a, b) ((a) ^= (b), (b) ^= (a), (a) ^= (b))#define writeln(x) (write(x), putchar('\n'))#define lowbit(x) ((x)&(-(x)))using namespace std;const int yzh = 1000000007, N = 1000000;void read(int &x) { char ch; bool flag = 0; for (ch = getchar(); !isdigit(ch) && ((flag |= (ch == '-')) || 1); ch = getchar()); for (x = 0; isdigit(ch); x = (x<<1)+(x<<3)+ch-48, ch = getchar()); x *= 1-2*flag;}void print(LL x) {if (x > 9) print(x/10); putchar(x%10+48); }void write(LL x) {if (x < 0) putchar('-'); print(Abs(x)); }char ch[N+5];int len, ans, nxt[N+5], cnt[N+5], p;void work() { scanf("%s", ch+1); len = strlen(ch+1), ans = 1, p = 0; cnt[1] = 1; for (int i = 2; i <= len; i++) { int j = nxt[i-1]; while (j && ch[j+1] != ch[i]) j = nxt[j]; if (ch[j+1] == ch[i]) ++j; nxt[i] = j, cnt[i] = cnt[j]+1; while (p && ch[p+1] != ch[i]) p = nxt[p]; if (ch[p+1] == ch[i]) ++p; while (p > (i>>1)) p = nxt[p]; ans = 1ll*ans*(cnt[p]+1)%yzh; } writeln(ans);}int main() { int t; read(t); while (t--) work(); return 0;}