- 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 444E.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 "slices"7)8 910func cf444E(in io.Reader, out io.Writer) {11 var n, tot int12 Fscan(in, &n)13 if n == 1 {14 Fprint(out, 0)15 return16 }17 18 type edge struct{ v, w, wt int }19 es := make([]edge, n-1)20 for i := range es {21 Fscan(in, &es[i].v, &es[i].w, &es[i].wt)22 }23 slices.SortFunc(es, func(a, b edge) int { return a.wt - b.wt })24 25 fa := make([]int, n)26 sz := make([]int, n)27 lim := make([]int, n)28 for i := range fa {29 fa[i] = i30 sz[i] = 131 Fscan(in, &lim[i])32 tot += lim[i]33 }34 find := func(x int) int {35 rt := x36 for fa[rt] != rt {37 rt = fa[rt]38 }39 for fa[x] != rt {40 fa[x], x = rt, fa[x]41 }42 return rt43 }44 45 for _, e := range es {46 v, w := find(e.v-1), find(e.w-1)47 fa[w] = v48 sz[v] += sz[w]49 lim[v] += lim[w]50 if sz[v] > tot-lim[v] {51 Fprint(out, e.wt)52 return53 }54 }55 Fprint(out, es[n-2].wt)56}57 5859