Approach
Sorting and greedy selection
For Codeforces 1605E — Array Equalizer, 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
- 74 lines of Go from the credited upstream file 1605E.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 "bufio"5 . "fmt"6 "io"7 "slices"8 "sort"9)10 1112func cf1605E(in io.Reader, _w io.Writer) {13 out := bufio.NewWriter(_w)14 defer out.Flush()15 var n, x, q int16 Fscan(in, &n)17 a := make([]int, n+1)18 for i := 1; i <= n; i++ {19 Fscan(in, &a[i])20 }21 for i := 1; i <= n; i++ {22 Fscan(in, &x)23 a[i] = x - a[i]24 }25 a[1]++26 27 b := make([]int, n+1)28 b[1] = 129 for i := 1; i <= n; i++ {30 for j := i * 2; j <= n; j += i {31 a[j] -= a[i]32 b[j] -= b[i]33 }34 }35 36 var c, e []int37 s := 038 for i := 1; i <= n; i++ {39 if b[i] == 0 {40 if a[i] < 0 {41 s += -a[i]42 } else {43 s += a[i]44 }45 } else if b[i] > 0 {46 c = append(c, a[i])47 } else {48 e = append(e, a[i])49 }50 }51 52 k, t := len(c), len(e)53 slices.Sort(c)54 sc := make([]int, k+1)55 for i, v := range c {56 sc[i+1] = sc[i] + v57 }58 slices.Sort(e)59 se := make([]int, t+1)60 for i, v := range e {61 se[i+1] = se[i] + v62 }63 64 Fscan(in, &q)65 for range q {66 Fscan(in, &x)67 i := sort.Search(k, func(i int) bool { return c[i] > -x })68 j := sort.Search(t, func(i int) bool { return e[i] > x })69 Fprintln(out, s+sc[k]-2*sc[i]+x*(k-2*i)+se[t]-2*se[j]-x*(t-2*j))70 }71}72 7374