- 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
- 99 lines of Go from the credited upstream file 1257D.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 "math/bits"8 "sort"9)10 1112func Sol1257D(reader io.Reader, writer io.Writer) {13 in := bufio.NewReader(reader)14 out := bufio.NewWriter(writer)15 defer out.Flush()16 17 max := func(a, b int) int {18 if a > b {19 return a20 }21 return b22 }23 var st [][18]int24 stInit := func(a []int) {25 n := len(a)26 st = make([][18]int, n)27 for i := range st {28 st[i][0] = a[i]29 }30 for j := uint(1); 1<<j <= n; j++ {31 for i := 0; i+(1<<j)-1 < n; i++ {32 st[i][j] = max(st[i][j-1], st[i+(1<<(j-1))][j-1])33 }34 }35 }36 stQuery := func(l, r int) int {37 k := uint(bits.Len(uint(r-l+1)) - 1)38 return max(st[l][k], st[r-(1<<k)+1][k])39 }40 type hero struct{ power, endurance int }41 42 var t int43 for Fscan(in, &t); t > 0; t-- {44 var n, m int45 Fscan(in, &n)46 a := make([]int, n)47 for i := range a {48 Fscan(in, &a[i])49 }50 stInit(a)51 Fscan(in, &m)52 heroes := make([]hero, m)53 for i := range heroes {54 Fscan(in, &heroes[i].power, &heroes[i].endurance)55 }56 sort.Slice(heroes, func(i, j int) bool {57 return heroes[i].endurance > heroes[j].endurance || heroes[i].endurance == heroes[j].endurance && heroes[i].power > heroes[j].power58 })59 60 maxPowers := make([]int, n+1)61 maxPower := 062 for i := 0; i < m; {63 hi := heroes[i]64 maxPower = max(maxPower, hi.power)65 j := i + 166 for ; j < m && heroes[j].endurance == hi.endurance; j++ {67 }68 nextEndurance := 069 if j < m {70 nextEndurance = heroes[j].endurance71 }72 for k := hi.endurance; k > nextEndurance; k-- {73 maxPowers[k] = maxPower74 }75 i = j76 }77 ans := 078 for l := 0; l < n; ans++ {79 maxKills := sort.Search(n-l+1, func(kills int) bool {80 if kills == 0 {81 return !true82 }83 maxMonsterPower := stQuery(l, l+kills-1)84 return !(maxMonsterPower <= maxPowers[kills])85 }) - 186 if maxKills == 0 {87 ans = -188 break89 }90 l += maxKills91 }92 Fprintln(out, ans)93 }94}95 96979899