- 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
- 53 lines of Go from the credited upstream file 652D.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 "sort"8)9 1011func CF652D(_r io.Reader, _w io.Writer) {12 in := bufio.NewReader(_r)13 out := bufio.NewWriter(_w)14 defer out.Flush()15 16 var n int17 Fscan(in, &n)18 ps := make([]struct{ v, i int }, n*2)19 for i := range ps {20 Fscan(in, &ps[i].v)21 ps[i].i = i22 }23 sort.Slice(ps, func(i, j int) bool { return ps[i].v < ps[j].v })24 kth := make([]int, n*2)25 for i, p := range ps {26 kth[p.i] = i + 127 }28 29 type pair struct{ l, r, i int }30 a := make([]pair, n)31 for i := range a {32 a[i] = pair{kth[i*2], kth[i*2+1], i}33 }34 sort.Slice(a, func(i, j int) bool { return a[i].r < a[j].r })35 ans := make([]int, n)36 tree := make([]int, n*2+1)37 for i, p := range a {38 c := i39 for i := p.l; i > 0; i &= i - 1 {40 c -= tree[i]41 }42 ans[p.i] = c43 for i := p.l; i <= n*2; i += i & -i {44 tree[i]++45 }46 }47 for _, v := range ans {48 Fprintln(out, v)49 }50}51 5253