- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 88 lines of Go from the credited upstream file 432D.go.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1package main2 3import (4 "bufio"5 . "fmt"6 "io"7 "sort"8)9 1011func CF432D(_r io.Reader, _w io.Writer) {12 in := bufio.NewReader(_r)13 out := bufio.NewWriter(_w)14 defer out.Flush()15 16 var s string17 Fscan(in, &s)18 n := len(s)19 z := make([]int, n)20 cnt := make([]int, n+2)21 l, r := 0, 022 for i := 1; i < n; i++ {23 if i <= r {24 z[i] = min(z[i-l], r-i+1)25 }26 for i+z[i] < n && s[z[i]] == s[i+z[i]] {27 l, r = i, i+z[i]28 z[i]++29 }30 cnt[z[i]]++31 }32 z[0] = n33 cnt[n]++34 35 ans := [][2]int{}36 for i := n; i > 0; i-- {37 cnt[i] += cnt[i+1]38 if z[n-i] == i {39 ans = append(ans, [2]int{i, cnt[i]})40 }41 }42 Fprintln(out, len(ans))43 for i := len(ans) - 1; i >= 0; i-- {44 p := ans[i]45 Fprintln(out, p[0], p[1])46 }47}48 4950func CF432D2(_r io.Reader, _w io.Writer) {51 in := bufio.NewReader(_r)52 out := bufio.NewWriter(_w)53 defer out.Flush()54 55 var s string56 Fscan(in, &s)57 n := len(s)58 z := make([]int, n)59 l, r := 0, 060 for i := 1; i < n; i++ {61 if i <= r {62 z[i] = min(z[i-l], r-i+1)63 }64 for i+z[i] < n && s[z[i]] == s[i+z[i]] {65 l, r = i, i+z[i]66 z[i]++67 }68 }69 z[0] = n70 71 sortedZ := append([]int{}, z...)72 sort.Ints(sortedZ)73 74 ans := [][2]int{}75 for i := 1; i <= n; i++ {76 if z[n-i] == i {77 j := sort.SearchInts(sortedZ, i)78 ans = append(ans, [2]int{i, n - j})79 }80 }81 Fprintln(out, len(ans))82 for _, p := range ans {83 Fprintln(out, p[0], p[1])84 }85}86 8788