- 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 1578L.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 cf1578L(in io.Reader, out io.Writer) {11 var n, m int12 Fscan(in, &n, &m)13 sum := make([]int, n+1)14 f := make([]int, n+1)15 for i := 1; i <= n; i++ {16 Fscan(in, &sum[i])17 f[i] = 1e1818 }19 type edge struct{ v, w, wt int }20 es := make([]edge, m)21 for i := range es {22 Fscan(in, &es[i].v, &es[i].w, &es[i].wt)23 }24 slices.SortFunc(es, func(a, b edge) int { return b.wt - a.wt })25 26 pa := make([]int, n+1)27 for i := range pa {28 pa[i] = i29 }30 find := func(x int) int {31 rt := x32 for pa[rt] != rt {33 rt = pa[rt]34 }35 for pa[x] != rt {36 pa[x], x = rt, pa[x]37 }38 return rt39 }40 41 for _, e := range es {42 x, y := find(e.v), find(e.w)43 if x == y {44 continue45 }46 f[y] = max(min(f[y], e.wt)-sum[x], min(f[x], e.wt)-sum[y])47 sum[y] += sum[x]48 pa[x] = y49 }50 51 ans := f[find(1)]52 if ans <= 0 {53 ans = -154 }55 Fprint(out, ans)56}57 5859