- 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
- 68 lines of Go from the credited upstream file 2023B.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 "container/heap"6 . "fmt"7 "io"8)9 1011func cf2023B(in io.Reader, _w io.Writer) {12 out := bufio.NewWriter(_w)13 defer out.Flush()14 var T, n int15 for Fscan(in, &T); T > 0; T-- {16 Fscan(in, &n)17 s := make([]int, n+1)18 for i := 1; i <= n; i++ {19 Fscan(in, &s[i])20 s[i] += s[i-1]21 }22 g := make([]int, n)23 for i := range g {24 Fscan(in, &g[i])25 g[i]--26 }27 28 ans := 029 dis := make([]int, n)30 for i := range dis {31 dis[i] = 1e1832 }33 dis[0] = 034 h := hp23{{}}35 for len(h) > 0 {36 top := heap.Pop(&h).(pair23)37 v := top.v38 d := top.dis39 if d > dis[v] {40 continue41 }42 ans = max(ans, s[v+1]-d)43 if v > 0 && d < dis[v-1] {44 dis[v-1] = d45 heap.Push(&h, pair23{d, v - 1})46 }47 if w := g[v]; w > v {48 d += s[v+1] - s[v]49 if d < dis[w] {50 dis[w] = d51 heap.Push(&h, pair23{d, w})52 }53 }54 }55 Fprintln(out, ans)56 }57}58 5960 61type pair23 struct{ dis, v int }62type hp23 []pair2363func (h hp23) Len() int { return len(h) }64func (h hp23) Less(i, j int) bool { return h[i].dis < h[j].dis }65func (h hp23) Swap(i, j int) { h[i], h[j] = h[j], h[i] }66func (h *hp23) Push(v any) { *h = append(*h, v.(pair23)) }67func (h *hp23) Pop() (v any) { a := *h; *h, v = a[:len(a)-1], a[len(a)-1]; return }68