Codeforces
CF Step
Youtube Linkedin Discord Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

Hints: A Trivial String Problem

$f(t)$ is the maximum number of contiguous parts in a partition of $t$ such that each part is a (non-empty) prefix of $t$ (the whole string), and the parts concatenate to $t$ in order.

For $t = \texttt{aaaaa}$, why is $f(t)=5$?

Answer to Hint 1: Each part can be the one-letter prefix a, so you can split into five copies of a. You cannot exceed $|t|$ parts, so $f(t)=|t|$ here.
Fix a left endpoint $l$. Every substring $s[l..j]$ rewrites as a prefix of the string $T = s[l..n]$ (reindexed to start at $0$). To compute all $f(T[0..x-1])$ for $x=1..|T|$, what linear-time structure encodes, for each position $p \ge 1$, how far $T$ matches $T[p..]$?
Answer to Hint 3: The Z-function $z[p]$ on $T$: $z[p]$ is the length of the longest common prefix of $T$ and $T[p..]$. Building $Z$ for $T$ is $O(|T|)$.

Answer to Hint 4: You now have $z[p]$ for all $p$ (the model sets $z[0]=|T|$ in build_z).

For each prefix length $x = 1..m$, let $F[x] = f(T[0..x-1])$. How does $F[x]$ relate to some earlier $F[\text{pre}]$ using intervals $[p,, p+z[p])$ for positions $p$ with $1 \le p \le x-1$?

Answer to Hint 5: Each position $p \ge 1$ contributes an interval $[p,, p+z[p])$ of “valid jumps”: from a prefix of length $\ge p+z[p]$ you could have transferred through the overlap structure. The model stacks these intervals while scanning $x$ and sets pre to the farthest feasible previous boundary still compatible with the stack—then $F[x] = F[\text{pre}] + 1$.

Answer to Hint 6: Maintain a stack of pairs (start, end) from positions $p$ with $p < x-1$; pop while the interval ends before $x$. Let pre be the start of the last surviving interval (or $0$ if empty). Then $F[x] = F[\text{pre}] + 1$ and pref[x] = pref[x-1] + F[x].

For query $(l,r)$ with $T$ built through length $r-l+1$, what is $\sum_{j=l}^{r} f(s[l..j])$ in terms of pref?

Answer to Hint 7: $\sum_{j=l}^{r} f(s[l..j]) = \sum_{x=1}^{r-l+1} F[x] = \texttt{pref}[r-l+1]$ for that $T$.

Answer to Hint 8: For a query $(l,r)$, build $T$ as the prefix of $s[l..n]$ of length $r-l+1$; then the sum equals $\texttt{pref}[r-l+1]$ computed on that $T$.

Several queries may share the same $l$. How do you avoid rebuilding $T$ and the Z-array for every query line?

Answer to Hint 9: Bucket queries by l. For each group, set m = max r - l + 1 over queries in the bucket, build one $T$ of length m, one Z-array, and one F/pref run; answer every query in that bucket via pref[r-l+1].

Why is $O(n \cdot q)$ acceptable here?

Answer to Hint 10: With $q \le 100$, even one distinct $l$ per query gives at most $100$ runs of $O(n)$ work each in the worst case, which fits $\sum n \le 10^6$.

Implementation: Store answers by query index; print in the original input order.