- 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
- 87 lines of Go from the credited upstream file 979D.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 "runtime/debug"8)9 1011func init() { debug.SetGCPercent(-1) }12 13type node79 struct {14 son [2]*node7915 min int16}17 18type trie79 struct{ root *node79 }19 20func (t *trie79) put(v int) *node79 {21 o := t.root22 if v < o.min {23 o.min = v24 }25 for i := 16; i >= 0; i-- {26 b := v >> i & 127 if o.son[b] == nil {28 o.son[b] = &node79{min: 2e9}29 }30 o = o.son[b]31 if v < o.min {32 o.min = v33 }34 }35 return o36}37 38func (t *trie79) maxXorWithLimitVal(v, limit int) (w int) {39 o := t.root40 if o.min > limit {41 return -142 }43 for i := 16; i >= 0; i-- {44 b := v >> i & 145 if o.son[b^1] != nil && o.son[b^1].min <= limit {46 b ^= 147 }48 w |= b << i49 o = o.son[b]50 }51 return52}53 54func CF979D(_r io.Reader, _w io.Writer) {55 in := bufio.NewReader(_r)56 out := bufio.NewWriter(_w)57 defer out.Flush()58 const mx int = 1e559 ds := [mx + 1][]int{}60 ts := [mx + 1]*trie79{}61 for i := 1; i <= mx; i++ {62 for j := i; j <= mx; j += i {63 ds[j] = append(ds[j], i)64 }65 ts[i] = &trie79{&node79{min: 2e9}}66 }67 has := [mx + 1]bool{}68 69 var q, t, x, k, s int70 for Fscan(in, &q); q > 0; q-- {71 if Fscan(in, &t, &x); t == 1 {72 if !has[x] {73 has[x] = true74 for _, d := range ds[x] {75 ts[d].put(x)76 }77 }78 } else if Fscan(in, &k, &s); x%k > 0 {79 Fprintln(out, -1)80 } else {81 Fprintln(out, ts[k].maxXorWithLimitVal(x, s-x))82 }83 }84}85 8687