- 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
- 62 lines of Go from the credited upstream file 1401E.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 . "fmt"5 "io"6)7 89type fenwick01 []int10 11func (t fenwick01) update(i, v int) {12 for ; i < len(t); i += i & -i {13 t[i] += v14 }15}16 17func (t fenwick01) pre(i int) (s int) {18 for ; i > 0; i &= i - 1 {19 s += t[i]20 }21 return22}23 24func cf1401E(in io.Reader, out io.Writer) {25 const mx int = 1e626 var n, m, x, l, r int27 Fscan(in, &n, &m)28 29 ans := 130 g := [mx + 2][]int{}31 for range n {32 Fscan(in, &x, &l, &r)33 g[l] = append(g[l], x<<1|1)34 g[r+1] = append(g[r+1], x<<1)35 if l == 0 && r == mx {36 ans++37 }38 }39 type pair struct{ l, r int }40 qs := [mx][]pair{}41 for range m {42 Fscan(in, &x, &l, &r)43 qs[x] = append(qs[x], pair{l, r})44 if l == 0 && r == mx {45 ans++46 }47 }48 49 t := make(fenwick01, mx+1)50 for i, qs := range qs[:] {51 for _, j := range g[i] {52 t.update(j>>1, j&1*2-1)53 }54 for _, q := range qs {55 ans += t.pre(q.r) - t.pre(q.l-1)56 }57 }58 Fprint(out, ans)59}60 6162