题目描述
https://codeforces.com/problemset/problem/961/F
简要题意:定义 $S$ 的 $k$ 子串为 $S_k=S[k..n-k+1],k\le \lceil\frac{n}{2}\rceil$,求 $S_k$ 的最长 $border$ 长度,$k\in [1,\lceil\frac{n}{2}\rceil]$
$|S|\le 10^6$
Solution
令 $ans_i$ 表示 $S_i$ 的最长 $border$,容易发现 $ans_i\le ans_{i+1}+2$,画图容易验证,那么我们暴力求 $ans_i$ 即可,判断相等使用 $hash$ 即可
时间复杂度 $O(n)$
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 56 57 58
| #include <iostream> #include <cstring> #define maxn 1000010 #define ll long long using namespace std;
struct Hash { const int base = 131; const ll p = 212370440130137957;
ll pow[maxn], h[maxn];
inline ll mul(ll x, ll y) { return (x * y - (ll) ((long double) x / p * y) * p + p) % p; } inline ll add(ll x, ll y) { return (x += y) >= p ? x - p : x; }
void init(char *s) { int l = strlen(s + 1); pow[0] = 1; for (int i = 1; i <= l; ++i) pow[i] = mul(pow[i - 1], base); for (int i = 1; i <= l; ++i) h[i] = add(s[i], mul(h[i - 1], base)); } ll get(int l, int r) { return add(h[r], p - mul(h[l - 1], pow[r - l + 1])); } ll hash(char *s) { int l = strlen(s + 1); ll ans = 0; for (int i = 1; i <= l; ++i) ans = add(s[i], mul(ans, base)); return ans; } } H;
int n; char s[maxn];
int ans[maxn]; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);
cin >> n >> s + 1; H.init(s); int m = (n + 1) / 2; ans[m] = (n & 1) ? 0 : s[n / 2] == s[n / 2 + 1]; for (int i = m - 1; i; --i) { ans[i] = ans[i + 1] + 2; while (i + ans[i] - 1 > n - i + 1) --ans[i]; while (ans[i] > 0) { if (i + ans[i] - 1 > n - i + 1 || (~ans[i] & 1) || H.get(i, i + ans[i] - 1) != H.get(n - i + 1 - ans[i] + 1, n - i + 1)) --ans[i]; else break; } } for (int i = 1; i <= m; ++i) { if (!ans[i]) ans[i] = -1; cout << ans[i] << " \n"[i == m]; } return 0; }
|