- 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
- 79 lines of Go from the credited upstream file 1399E2.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 CF1399E2(_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 a18 }19 return b20 }21 type nb struct{ to, wt, c int }22 23 var T, n, v, w, wt, c int24 var s int6425 for Fscan(in, &T); T > 0; T-- {26 Fscan(in, &n, &s)27 g := make([][]nb, n)28 for i := 1; i < n; i++ {29 Fscan(in, &v, &w, &wt, &c)30 v--31 w--32 g[v] = append(g[v], nb{w, wt, c})33 g[w] = append(g[w], nb{v, wt, c})34 }35 g[0] = append(g[0], nb{-1, 0, 0})36 a, tot := [3][]int64{}, int64(0)37 var f func(v, fa int) int6438 f = func(v, fa int) (leaf int64) {39 if len(g[v]) == 1 {40 return 141 }42 for _, e := range g[v] {43 if e.to != fa {44 c := f(e.to, v)45 wt := int64(e.wt)46 tot += wt * c47 for ; wt > 0; wt >>= 1 {48 a[e.c] = append(a[e.c], (wt+1)/2*c)49 }50 leaf += c51 }52 }53 return54 }55 f(0, -1)56 57 for _, b := range a {58 sort.Slice(b, func(i, j int) bool { return b[i] > b[j] })59 }60 m := len(a[2])61 s2 := make([]int64, m+1)62 for i, v := range a[2] {63 s2[i+1] = s2[i] + v64 }65 66 ans := int(1e9)67 a[1] = append(a[1], 0)68 for i, v := range a[1] {69 if j := sort.Search(m+1, func(j int) bool { return tot-s2[j] <= s }); j <= m {70 ans = min(ans, i+2*j)71 }72 tot -= v73 }74 Fprintln(out, ans)75 }76}77 7879