- 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 2185H.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 cf2185H(in io.Reader, _w io.Writer) {12 out := bufio.NewWriter(_w)13 defer out.Flush()14 var T, n, k int15 for Fscan(in, &T); T > 0; T-- {16 Fscan(in, &n, &k)17 a := make([]int, n+1)18 s := make([]int, n+1)19 p := []int{}20 for i := 1; i <= n; i++ {21 Fscan(in, &a[i])22 s[i] = s[i-1] + a[i]23 if a[i] > s[i-1] {24 p = append(p, i)25 }26 }27 28 for i := 1; i <= n; i++ {29 h := []int{}30 for _, x := range p {31 if x == i {32 continue33 }34 ex := 035 if x < i {36 ex = a[i]37 }38 if a[x] > s[x-1]+ex {39 h = append(h, x)40 }41 }42 43 if len(h) < k {44 Fprint(out, n, " ")45 continue46 }47 ans := 048 if k > 0 {49 x := h[len(h)-k]50 ans = n - x51 if x >= i {52 ans++53 }54 }55 if len(h) == k {56 le := 057 if s[i-1] < a[i] {58 le = 159 }60 v := (le + 1) * a[i]61 j := sort.Search(n, func(j int) bool { return s[j+1] >= v }) + 162 ans += j - le63 }64 Fprint(out, ans, " ")65 }66 Fprintln(out)67 }68}69 7071