- 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
- 96 lines of Go from the credited upstream file 1993F2.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 . "fmt"5 "io"6)7 89func cf1993F2(in io.Reader, out io.Writer) {10 var T, N, k, m, n int11 var str string12 for Fscan(in, &T); T > 0; T-- {13 Fscan(in, &N, &k, &m, &n, &str)14 n *= 215 m *= 216 px := make([]int, N+1)17 py := make([]int, N+1)18 for i, b := range str {19 addX := 020 if b == 'D' {21 addX = n - 122 } else if b == 'U' {23 addX = 124 }25 px[i+1] = (px[i] + addX) % n26 27 addY := 028 if b == 'L' {29 addY = m - 130 } else if b == 'R' {31 addY = 132 }33 py[i+1] = (py[i] + addY) % m34 }35 36 dx := px[N]37 dy := py[N]38 gx := gcd93(dx, n)39 gy := gcd93(dy, m)40 p := n / gx41 q := m / gy42 dx /= gx43 dy /= gy44 ix := inv93(dx, p)45 iy := inv93(dy, q)46 d, u, _ := exgcd93(p, q)47 e := p / d * q48 49 ans := 050 for i := 1; i <= N; i++ {51 rx := (n - px[i]) % n52 ry := (m - py[i]) % m53 if rx%gx != 0 || ry%gy != 0 {54 continue55 }56 57 rx = rx / gx * ix % p58 ry = ry / gy * iy % q59 if (ry-rx)%d != 0 {60 continue61 }62 63 z := q / d64 s := (((ry-rx)/d*u)%z + z) % z65 k0 := s*p + rx66 if k0 < k {67 ans += (k-k0-1)/e + 168 }69 }70 Fprintln(out, ans)71 }72}73 7475 76func exgcd93(a, b int) (gcd, x, y int) {77 if b == 0 {78 return a, 1, 079 }80 gcd, y, x = exgcd93(b, a%b)81 y -= a / b * x82 return83}84 85func inv93(a, m int) int {86 _, x, _ := exgcd93(a, m)87 return (x%m + m) % m88}89 90func gcd93(a, b int) int {91 for a != 0 {92 a, b = b%a, a93 }94 return b95}96