- 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
- 80 lines of Go from the credited upstream file 982E.go.
- The implementation keeps its working state in language-native values and containers.
- 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 cf982E(in io.Reader, out io.Writer) {10 var n, m, x, y, vx, vy int11 Fscan(in, &n, &m, &x, &y, &vx, &vy)12 13 if vx == 0 {14 if 0 < x && x < n {15 Fprint(out, -1)16 } else if vy < 0 {17 Fprint(out, x, 0)18 } else {19 Fprint(out, x, m)20 }21 return22 }23 24 if vy == 0 {25 if 0 < y && y < m {26 Fprint(out, -1)27 } else if vx < 0 {28 Fprint(out, 0, y)29 } else {30 Fprint(out, n, y)31 }32 return33 }34 35 k1 := x % n36 if vx > 0 {37 k1 = (n - x) % n38 }39 40 k2 := y % m41 if vy > 0 {42 k2 = (m - y) % m43 }44 45 g := gcd82(n, m)46 if (k1-k2)%g != 0 {47 Fprint(out, -1)48 return49 }50 51 lcm := n / g * m52 _, xx, _ := exgcd82(n, m)53 xx *= (k2 - k1) / g54 xx %= m / g55 s := ((xx*n+k1)%lcm + lcm) % lcm56 ansX := x + s*vx57 ansY := y + s*vy58 n *= 259 m *= 260 Fprint(out, (ansX%n+n)%n, (ansY%m+m)%m)61}62 6364 65func exgcd82(a, b int) (g, x, y int) {66 if b == 0 {67 return a, 1, 068 }69 g, y, x = exgcd82(b, a%b)70 y -= a / b * x71 return72}73 74func gcd82(a, b int) int {75 for a != 0 {76 a, b = b%a, a77 }78 return b79}80