- 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
- 59 lines of Go from the credited upstream file 1528A.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 CF1528A(_r io.Reader, _w io.Writer) {11 in := bufio.NewReader(_r)12 out := bufio.NewWriter(_w)13 defer out.Flush()14 max := func(a, b int64) int64 {15 if a > b {16 return a17 }18 return b19 }20 abs := func(x int) int64 {21 if x < 0 {22 return int64(-x)23 }24 return int64(x)25 }26 27 var T, n, v, w int28 for Fscan(in, &T); T > 0; T-- {29 Fscan(in, &n)30 a := make([]struct{ l, r int }, n)31 for i := range a {32 Fscan(in, &a[i].l, &a[i].r)33 }34 type nb struct{ to, wt int }35 g := make([][]int, n)36 for i := 1; i < n; i++ {37 Fscan(in, &v, &w)38 v--39 w--40 g[v] = append(g[v], w)41 g[w] = append(g[w], v)42 }43 var f func(v, fa int) (sl, sr int64)44 f = func(v, fa int) (sl, sr int64) {45 for _, w := range g[v] {46 if w != fa {47 p, q := f(w, v)48 sl += max(abs(a[v].l-a[w].l)+p, abs(a[v].l-a[w].r)+q)49 sr += max(abs(a[v].r-a[w].l)+p, abs(a[v].r-a[w].r)+q)50 }51 }52 return53 }54 Fprintln(out, max(f(0, -1)))55 }56}57 5859