Approach
Sorting and greedy selection
For Codeforces 220E — Little Elephant and Inversions, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 72 lines of Go from the credited upstream file 220E.go.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
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 "slices"7 "sort"8)9 1011type fenwick20 []int12 13func (f fenwick20) update(i, val int) {14 for ; i < len(f); i += i & -i {15 f[i] += val16 }17}18 1920func (f fenwick20) sum(i int) (res int) {21 for ; i > 0; i &= i - 1 {22 res += f[i]23 }24 return25}26 27func cf220E(in io.Reader, out io.Writer) {28 var n, k, ans int29 Fscan(in, &n, &k)30 a := make([]int, n)31 for i := range a {32 Fscan(in, &a[i])33 }34 35 b := slices.Clone(a)36 slices.Sort(b)37 b = slices.Compact(b)38 m := len(b)39 40 41 suf := make(fenwick20, m+1)42 for i := n - 1; i >= 0; i-- {43 a[i] = sort.SearchInts(b, a[i]) + 1 44 k -= suf.sum(a[i] - 1)45 suf.update(a[i], 1)46 }47 48 pre := make(fenwick20, m+1)49 l := 050 for r := 1; r < n; r++ {51 52 suf.update(a[r-1], -1)53 k += l - pre.sum(a[r-1]) + suf.sum(a[r-1]-1)54 for l < r {55 56 inv := l - pre.sum(a[l]) + suf.sum(a[l]-1)57 if inv > k { 58 break59 }60 61 k -= inv62 pre.update(a[l], 1)63 l++64 }65 66 ans += l67 }68 Fprint(out, ans)69}70 7172