- 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
- 63 lines of Go from the credited upstream file 61E.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 CF61E(_r io.Reader, out io.Writer) {12 in := bufio.NewReader(_r)13 var n int14 Fscan(in, &n)15 ps := make([]struct{ v, i int }, n)16 for i := range ps {17 Fscan(in, &ps[i].v)18 ps[i].i = i19 }20 sort.Slice(ps, func(i, j int) bool { return ps[i].v < ps[j].v })21 a := make([]int, n)22 for i, p := range ps {23 a[p.i] = i + 124 }25 26 tree := make([]int, n+1)27 add := func(i int) {28 for ; i <= n; i += i & -i {29 tree[i]++30 }31 }32 sum := func(i int) (res int) {33 for ; i > 0; i &= i - 1 {34 res += tree[i]35 }36 return37 }38 query := func(l, r int) int { return sum(r) - sum(l-1) }39 tree2 := make([]int64, n+1)40 add2 := func(i, val int) {41 for ; i <= n; i += i & -i {42 tree2[i] += int64(val)43 }44 }45 sum2 := func(i int) (res int64) {46 for ; i > 0; i &= i - 1 {47 res += tree2[i]48 }49 return50 }51 query2 := func(l, r int) int64 { return sum2(r) - sum2(l-1) }52 53 ans := int64(0)54 for _, v := range a {55 ans += query2(v+1, n)56 add2(v, query(v+1, n))57 add(v)58 }59 Fprint(out, ans)60}61 6263