- 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
- 105 lines of Go from the credited upstream file 920D.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 CF920D(_r io.Reader, _w io.Writer) {11 in := bufio.NewReader(_r)12 out := bufio.NewWriter(_w)13 defer out.Flush()14 const inf int = 1e915 16 var n, k, tar, tot, s1 int17 Fscan(in, &n, &k, &tar)18 a := make([]int, n)19 for i := range a {20 Fscan(in, &a[i])21 tot += a[i]22 }23 if tot < tar {24 Fprint(out, "NO")25 return26 }27 if tar%k == 0 {28 Fprintln(out, "YES")29 for i := 2; i <= n; i++ {30 Fprintln(out, inf, i, 1)31 }32 if tar > 0 {33 Fprintln(out, tar/k, 1, 2)34 }35 return36 }37 38 vis := make([][]bool, n)39 for i := range vis {40 vis[i] = make([]bool, k)41 }42 tarPos1 := 043 used := make([]bool, n)44 var f func(int, int) bool45 f = func(i, v int) bool {46 if v == tar%k {47 Fprintln(out, "YES")48 tarPos1 = i - 149 used[i-1] = true50 s1 += a[i-1]51 return true52 }53 if i == n || vis[i][v] {54 return false55 }56 vis[i][v] = true57 if f(i+1, v) {58 return true59 }60 if f(i+1, (v+a[i])%k) {61 if i != tarPos1 {62 used[i] = true63 s1 += a[i]64 Fprintln(out, inf, i+1, tarPos1+1)65 }66 return true67 }68 return false69 }70 if !f(0, 0) {71 Fprint(out, "NO")72 return73 }74 75 tarPos2 := -176 for i, u := range used {77 if !u {78 tarPos2 = i79 break80 }81 }82 if tarPos2 < 0 {83 if s1 > tar {84 tarPos2 = 085 if tarPos1 == 0 {86 tarPos2 = 187 }88 Fprintln(out, (s1-tar)/k, tarPos1+1, tarPos2+1)89 }90 return91 }92 for i, u := range used {93 if !u && i != tarPos2 {94 Fprintln(out, inf, i+1, tarPos2+1)95 }96 }97 if s1 < tar {98 Fprintln(out, (tar-s1)/k, tarPos2+1, tarPos1+1)99 } else if s1 > tar {100 Fprintln(out, (s1-tar)/k, tarPos1+1, tarPos2+1)101 }102}103 104105