- 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
- 75 lines of Go from the credited upstream file 1380D.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 CF1380D(_r io.Reader, out io.Writer) {11 in := bufio.NewReader(_r)12 var n, m, r int13 var x, k, y, s int6414 Fscan(in, &n, &m, &x, &k, &y)15 a := make([]int, n)16 pos := make([]int, n+1)17 for i := range a {18 Fscan(in, &a[i])19 pos[a[i]] = i20 }21 22 l := -123 f := func() bool {24 cnt := int64(r - l - 1)25 if cnt < 0 {26 return true27 }28 max := 029 for _, v := range a[l+1 : r] {30 if v > max {31 max = v32 }33 }34 edge := 035 if l >= 0 {36 edge = a[l]37 }38 if r < n && a[r] > edge {39 edge = a[r]40 }41 if cnt < k {42 if max > edge {43 return true44 }45 s += cnt * y46 } else if k*y < x {47 if max < edge {48 s += cnt * y49 } else {50 s += (cnt-k)*y + x51 }52 } else {53 s += cnt%k*y + cnt/k*x54 }55 return false56 }57 for ; m > 0; m-- {58 Fscan(in, &r)59 r = pos[r]60 if f() {61 Fprint(out, -1)62 return63 }64 l = r65 }66 r = n67 if f() {68 Fprint(out, -1)69 return70 }71 Fprint(out, s)72}73 7475