- 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 1860E.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 "slices"8)9 1011func cf1860E(in io.Reader, _w io.Writer) {12 abs := func(x int) int {13 if x < 0 {14 return -x15 }16 return x17 }18 out := bufio.NewWriter(_w)19 defer out.Flush()20 var s string21 var m, now int22 Fscan(in, &s, &m)23 g := [26][26][]int{}24 n := len(s)25 for i := 1; i < n; i++ {26 v, w := s[i-1]-'a', s[i]-'a'27 g[v][w] = append(g[v][w], i)28 }29 30 qs := make([]struct{ x, y int }, m)31 ans := make([]int, m)32 for i := range qs {33 Fscan(in, &qs[i].x, &qs[i].y)34 ans[i] = abs(qs[i].x - qs[i].y)35 }36 37 vis := [26][26]int{}38 dis := make([]int, n)39 for x := range 26 {40 for y := range 26 {41 if g[x][y] == nil {42 continue43 }44 for i := range dis {45 dis[i] = 1e946 }47 now++48 vis[x][y] = now49 q := slices.Clone(g[x][y])50 for _, i := range q {51 dis[i] = 052 }53 push := func(v, w int) {54 if dis[w] == 1e9 {55 dis[w] = dis[v] + 156 q = append(q, w)57 }58 }59 60 for len(q) > 0 {61 i := q[0]62 q = q[1:]63 if i > 1 {64 push(i, i-1)65 }66 if i < n-1 {67 push(i, i+1)68 }69 a, b := s[i-1]-'a', s[i]-'a'70 if vis[a][b] < now {71 vis[a][b] = now72 for _, j := range g[a][b] {73 push(i, j)74 }75 }76 }77 for i, q := range qs {78 ans[i] = min(ans[i], dis[q.x]+dis[q.y]+1)79 }80 }81 }82 for _, v := range ans {83 Fprintln(out, v)84 }85}86 8788