- 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
- 97 lines of Go from the credited upstream file 1874B.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)8 910func cf1874B(in io.Reader, _w io.Writer) {11 out := bufio.NewWriter(_w)12 defer out.Flush()13 pow5 := [8]int{1}14 for i := 1; i < 8; i++ {15 pow5[i] = pow5[i-1] * 516 }17 18 st := 019 for i, p5 := range pow5 {20 st += i & 3 * p521 }22 23 f := make([]int, pow5[7]*5)24 for i := range f {25 f[i] = 1e926 }27 f[st] = 028 q := []int{st}29 for len(q) > 0 {30 mask := q[0]31 q = q[1:]32 for op := range 4 {33 newMask := 034 for i, p5 := range pow5 {35 cd := mask / p5 % 536 c, d := cd>>1, cd&137 switch op {38 case 0:39 c &= d40 case 1:41 c |= d42 case 2:43 d ^= c44 default:45 d ^= i >> 246 }47 newMask += (c<<1 | d) * p548 }49 if f[newMask] == 1e9 {50 f[newMask] = f[mask] + 151 q = append(q, newMask)52 }53 }54 }55 for mask := range f {56 for _, p5 := range pow5 {57 if mask/p5%5 == 4 {58 for i := 1; i < 5; i++ {59 f[mask] = min(f[mask], f[mask-i*p5])60 }61 break62 }63 }64 }65 66 var T, a, b, c, d, m int67 mp := [8]int{}68o:69 for Fscan(in, &T); T > 0; T-- {70 Fscan(in, &a, &b, &c, &d, &m)71 for i := range mp {72 mp[i] = 473 }74 for i := range 30 {75 mab := m>>i&1<<2 | a>>i&1<<1 | b>>i&176 cd := c>>i&1<<1 | d>>i&177 if mp[mab] == 4 {78 mp[mab] = cd79 } else if mp[mab] != cd {80 Fprintln(out, -1)81 continue o82 }83 }84 mask := 085 for i, cd := range mp {86 mask += cd * pow5[i]87 }88 if f[mask] == 1e9 {89 Fprintln(out, -1)90 } else {91 Fprintln(out, f[mask])92 }93 }94}95 9697