- 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
- 72 lines of Go from the credited upstream file 722C.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 CF722C(_r io.Reader, _w io.Writer) {11 in := bufio.NewReader(_r)12 out := bufio.NewWriter(_w)13 defer out.Flush()14 var fa []int15 initFa := func(n int) {16 fa = make([]int, n)17 for i := range fa {18 fa[i] = i19 }20 }21 var find func(int) int22 find = func(x int) int {23 if fa[x] != x {24 fa[x] = find(fa[x])25 }26 return fa[x]27 }28 29 var n int30 Fscan(in, &n)31 arr := make([]int, n)32 for i := range arr {33 Fscan(in, &arr[i])34 }35 pos := make([]int, n)36 for i := range pos {37 Fscan(in, &pos[i])38 }39 40 ans := make([]int64, n)41 vis := make([]bool, n+2)42 sum := make([]int64, n+1)43 initFa(n + 1)44 max := int64(0)45 for i := n - 1; i >= 0; i-- {46 ans[i] = max47 p := pos[i]48 vis[p] = true49 sum[p] += int64(arr[p-1])50 if vis[p-1] {51 f := find(p - 1)52 sum[p] += sum[f]53 fa[f] = p54 }55 if vis[p+1] {56 f := find(p + 1)57 sum[p] += sum[f]58 fa[f] = p59 }60 if sum[p] > max {61 max = sum[p]62 }63 }64 for _, v := range ans {65 Fprintln(out, v)66 }67}68 69707172