- 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
- 67 lines of Go from the credited upstream file 1832D2.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 "sort"8)9 1011func CF1832D2(_r io.Reader, _w io.Writer) {12 in := bufio.NewReader(_r)13 out := bufio.NewWriter(_w)14 defer out.Flush()15 min := func(a, b int) int {16 if a > b {17 return b18 }19 return a20 }21 22 var n, q, k, ans int23 Fscan(in, &n, &q)24 a := make([]int, n)25 s := -int64(n-1) * int64(n-2) / 226 for i := range a {27 Fscan(in, &a[i])28 s += int64(a[i])29 }30 sort.Ints(a)31 pre := make([]int, n)32 pre[0] = a[0]33 for i := 1; i < n; i++ {34 pre[i] = min(pre[i-1], a[i]-i)35 }36 for ; q > 0; q-- {37 Fscan(in, &k)38 if k < n {39 ans = min(pre[k-1]+k, a[k])40 } else if n == 1 {41 ans = a[0] - k/242 if k%2 > 0 {43 ans += k44 }45 } else {46 s := s + int64(k)*int64(n-1)47 ans = pre[n-2] + k48 k -= n - 149 if k%2 > 0 {50 s += int64(k)51 ans = min(ans, a[n-1]+k)52 k--53 } else {54 ans = min(ans, a[n-1])55 }56 s -= int64(ans) * int64(n)57 k /= 258 if int64(k) > s {59 ans -= (k-int(s)-1)/n + 160 }61 }62 Fprint(out, ans, " ")63 }64}65 6667