- 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
- 73 lines of Go from the credited upstream file 1903D2.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 "bufio"5 . "fmt"6 "io"7 "math/bits"8)9 1011func cf1903D2(in io.Reader, _w io.Writer) {12 out := bufio.NewWriter(_w)13 defer out.Flush()14 var n, q, v, k, total, maxVal int15 Fscan(in, &n, &q)16 17 const w = 2018 const u = 1 << w19 cnt := [u]int{}20 f := [u][w]int{}21 for range n {22 Fscan(in, &v)23 total += v24 maxVal = max(maxVal, v)25 cnt[v]++26 27 for j := uint32(u - 1 ^ v); j > 0; j &= j - 1 {28 i := bits.TrailingZeros32(j)29 f[v][i] += v & (1<<i - 1) 30 }31 }32 33 34 35 36 for i := range w {37 for s := 0; s < u; s++ {38 s |= 1 << i39 cnt[s^1<<i] += cnt[s]40 for j := range w {41 f[s^1<<i][j] += f[s][j]42 }43 }44 }45 46 for range q {47 Fscan(in, &k)48 avg := (total + k) / n49 if avg >= maxVal {50 Fprintln(out, avg)51 continue52 }53 ans := 054 for i := w - 1; i >= 0; i-- {55 56 57 58 59 60 61 62 cost := (n-cnt[ans|1<<i])<<i - f[ans][i]63 if cost <= k {64 k -= cost65 ans |= 1 << i66 }67 }68 Fprintln(out, ans)69 }70}71 7273