- 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
- 62 lines of Go from the credited upstream file 743D.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 CF743D(_r io.Reader, out io.Writer) {11 in := bufio.NewReader(_r)12 max := func(a, b int64) int64 {13 if b > a {14 return b15 }16 return a17 }18 const inf int64 = 1e1819 20 var n, v, w int21 Fscan(in, &n)22 a := make([]int, n)23 for i := range a {24 Fscan(in, &a[i])25 }26 g := make([][]int, n)27 for i := 1; i < n; i++ {28 Fscan(in, &v, &w)29 v--30 w--31 g[v] = append(g[v], w)32 g[w] = append(g[w], v)33 }34 35 ans := -inf36 var f func(int, int) (int64, int64)37 f = func(v, fa int) (int64, int64) {38 sum, fi, se := int64(a[v]), -inf*2, -inf*239 for _, w := range g[v] {40 if w != fa {41 s, mx := f(w, v)42 sum += s43 if mx > fi {44 fi, se = mx, fi45 } else if mx > se {46 se = mx47 }48 }49 }50 ans = max(ans, fi+se)51 return sum, max(sum, fi)52 }53 f(0, -1)54 if ans == -inf {55 Fprint(out, "Impossible")56 } else {57 Fprint(out, ans)58 }59}60 6162