- 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
- 71 lines of Go from the credited upstream file 2097C.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 cf2097C(in io.Reader, out io.Writer) {10 gcd := func(a, b int) int {11 for a != 0 {12 a, b = b%a, a13 }14 return b15 }16 abs := func(x int) int {17 if x < 0 {18 return -x19 }20 return x21 }22 23 var T, n, x, y, dx, dy int24 for Fscan(in, &T); T > 0; T-- {25 Fscan(in, &n, &x, &y, &dx, &dy)26 27 g := gcd(dx, dy)28 dx /= g29 dy /= g30 31 d := x*dy - y*dx32 if d%n != 0 {33 Fprintln(out, -1)34 continue35 }36 d /= n37 38 _, p, q := exgcd97(dy, dx)39 p *= d40 q *= -d41 42 if p <= 0 {43 v := (dx - p) / dx44 p += v * dx45 q += v * dy46 }47 if q <= 0 {48 v := (dy - q) / dy49 p += v * dx50 q += v * dy51 }52 53 v := min((p-1)/dx, (q-1)/dy)54 p -= v * dx55 q -= v * dy56 57 Fprintln(out, p-1+q-1+(p+q)/2+abs(p-q)/2)58 }59}60 6162 63func exgcd97(a, b int) (gcd, x, y int) {64 if b == 0 {65 return a, 1, 066 }67 gcd, y, x = exgcd97(b, a%b)68 y -= a / b * x69 return70}71