- 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
- 57 lines of Go from the credited upstream file 1394B.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 "math/rand"8 "sort"9 "time"10)11 1213func CF1394B(_r io.Reader, out io.Writer) {14 rand.Seed(time.Now().UnixNano())15 in := bufio.NewReader(_r)16 var n, m, k, v, w, wt, total, ans int17 Fscan(in, &n, &m, &k)18 type nb struct{ to, wt int }19 g := make([][]nb, n)20 for ; m > 0; m-- {21 Fscan(in, &v, &w, &wt)22 g[v-1] = append(g[v-1], nb{w - 1, wt})23 }24 25 h := make([]int, n) 26 for i := range h {27 h[i] = rand.Int()28 total += h[i]29 }30 sumTo := make([][]int, k+1)31 for i := range sumTo {32 sumTo[i] = make([]int, i)33 }34 for _, es := range g {35 sort.Slice(es, func(i, j int) bool { return es[i].wt < es[j].wt })36 for i, e := range es {37 sumTo[len(es)][i] += h[e.to]38 }39 }40 var f func(int, int)41 f = func(p, tot int) {42 if p > k {43 if tot == total {44 ans++45 }46 return47 }48 for _, s := range sumTo[p][:p] {49 f(p+1, tot+s)50 }51 }52 f(1, 0)53 Fprint(out, ans)54}55 5657