P2375 [NOI2014] 动物园
如果没有“不重叠”的限制,即为 KMP 的 next 数组。现在要求长度不能超过串的一半,那么就反复跳 next 直到得到答案为止。
查看代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| #include <cstdio> #include <cstring> using namespace std; template <class Type> void read (Type &x) { char c; bool flag = false; while ((c = getchar()) < '0' || c > '9') if (c == '-') flag = true; x = c - '0'; while ((c = getchar()) >= '0' && c <= '9') x = (x << 3) + (x << 1) + c - '0'; if (flag) x = ~x + 1; } template <class Type, class ...Rest> void read (Type &x, Rest &...y) { read(x), read(y...); } template <class Type> void write (Type x) { if (x < 0) putchar('-'), x = ~x + 1; if (x > 9) write(x / 10); putchar('0' + x % 10); } typedef long long L; const int N = 1e6 + 10, mod = 1e9 + 7; char s[N]; int n, nxt[N], f[N]; int main () { int T; read(T); while (T--) { scanf("%s", s + 1); n = strlen(s + 1); f[1] = 1; for (int i = 2, j = 0; i <= n; ++i) { while (j && s[i] != s[j + 1]) j = nxt[j]; if (j < n && s[i] == s[j + 1]) ++j; nxt[i] = j; f[i] = f[j] + 1; } int res = 1; for (int i = 2, j = 0; i <= n; ++i) { while (j && s[i] != s[j + 1]) j = nxt[j]; if (j < n && s[i] == s[j + 1]) ++j; while (j << 1 > i) j = nxt[j]; res = (L)res * (f[j] + 1) % mod; } write(res), puts(""); } return 0; }
|