洛谷
给定一个字符串 \(s\),找到最小的 \(t\) 使得 \(t\) 匹配的位置能覆盖 \(s\)。
\(t\) 一定是 \(s\) 的一个前后缀(\(s\) 也算),考虑 DP。设 \(f_i\) 表示前缀 \(i\) 的答案,那么 \(f_i\) 要么是 \(i\),要么是 \(f_{\mathrm{border}(i)}\)。那么如果是 \(f_{\mathrm{border}(i)}\),那么某个 \(f_j=f_{\mathrm{border}(i)}\) 一定在 \([i-\mathrm{border}(i),i]\) 内。
const int N = 5e5 + 10; inline ll Read() { ll x = 0, f = 1; char c = getchar(); while (c != '-' && (c < '0' || c > '9')) c = getchar(); if (c == '-') f = -f, c = getchar(); while (c >= '0' && c <= '9') x = (x << 3) + (x << 1) + c - '0', c = getchar(); return x * f; } char s[N]; int nxt[N], f[N], g[N];; int main() { // freopen(".in", "r", stdin); // freopen(".out", "w", stdout); scanf ("%s", s + 1); int n = strlen (s + 1); for (int i = 2, j = 0; i <= n; i++) { while (j && s[i] != s[j + 1]) j = nxt[j]; if (s[i] == s[j + 1]) j++; nxt[i] = j; } for (int i = 1; i <= n; i++) { f[i] = i; if (g[f[nxt[i]]] >= i - nxt[i]) f[i] = f[nxt[i]]; g[f[i]] = i; } printf ("%d\n", f[n]); return 0; }