- 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
- 83 lines of Go from the credited upstream file 915F.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 . "fmt"5 "io"6 "sort"7)8 910func CF915F(_r io.Reader, out io.Writer) {11 buf := make([]byte, 1<<12)12 _i := len(buf)13 rc := func() byte {14 if _i >= len(buf) {15 _r.Read(buf)16 _i = 017 }18 b := buf[_i]19 _i++20 return b21 }22 r := func() (x int) {23 b := rc()24 for ; '0' > b; b = rc() {25 }26 for ; '0' <= b; b = rc() {27 x = x*10 + int(b&15)28 }29 return30 }31 n := r()32 a := make([]int, n)33 for i := range a {34 a[i] = r()35 }36 es := make([]struct{ v, w int }, n-1)37 for i := range es {38 v, w := r()-1, r()-139 if a[v] > a[w] {40 v, w = w, v41 }42 es[i].v = v43 es[i].w = w44 }45 46 sort.Slice(es, func(i, j int) bool { return a[es[i].w] < a[es[j].w] })47 fa := make([]int, n)48 sz := make([]int, n)49 for i := range fa {50 fa[i] = i51 sz[i] = 152 }53 var find func(int) int54 find = func(x int) int {55 if fa[x] != x {56 fa[x] = find(fa[x])57 }58 return fa[x]59 }60 ans := int64(0)61 for _, e := range es {62 v, w := find(e.v), find(e.w)63 ans += int64(sz[v]) * int64(sz[w]) * int64(a[e.w])64 fa[v] = w65 sz[w] += sz[v]66 }67 68 sort.Slice(es, func(i, j int) bool { return a[es[i].v] > a[es[j].v] })69 for i := range fa {70 fa[i] = i71 sz[i] = 172 }73 for _, e := range es {74 v, w := find(e.v), find(e.w)75 ans -= int64(sz[v]) * int64(sz[w]) * int64(a[e.v])76 fa[v] = w77 sz[w] += sz[v]78 }79 Fprint(out, ans)80}81 8283