- 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
- 60 lines of Go from the credited upstream file 1443E.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 cf1443E(in io.Reader, _w io.Writer) {11 out := bufio.NewWriter(_w)12 defer out.Flush()13 const mx = 1414 fac := [mx + 1]int{1}15 for i := 1; i <= mx; i++ {16 fac[i] = fac[i-1] * i17 }18 19 var n, q, op, l, r, k int20 Fscanln(in, &n, &q)21 m := min(n, mx)22 s := make([]int, m+1)23 valid := make([]int, m+1)24 kthPermutation := func(k int) {25 for i := 1; i <= m; i++ {26 valid[i] = 127 }28 for i := 1; i <= m; i++ {29 order := k/fac[m-i] + 130 k %= fac[m-i]31 for j := 1; j <= m; j++ {32 order -= valid[j]33 if order == 0 {34 s[i] = s[i-1] + j35 valid[j] = 036 break37 }38 }39 }40 }41 pre := func(r int) (res int) {42 d := max(n-mx, 0)43 mid := min(r, d)44 r = max(r-d, 0)45 return mid*(mid+1)/2 + s[r] + r*d46 }47 48 for range q {49 Fscanln(in, &op, &l, &r)50 if op == 1 {51 kthPermutation(k)52 Fprintln(out, pre(r)-pre(l-1))53 } else {54 k = (k + l) % fac[m]55 }56 }57}58 5960