Approach
Sorting and greedy selection
For Codeforces 1986E — Beautiful Array, 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
- 52 lines of Go from the credited upstream file 1986E.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)8 910func cf1986E(in io.Reader, out io.Writer) {11 var T, n, k, v int12 for Fscan(in, &T); T > 0; T-- {13 Fscan(in, &n, &k)14 g := map[int][]int{}15 for range n {16 Fscan(in, &v)17 g[v%k] = append(g[v%k], v/k)18 }19 20 ans := 021 odd := false22 for _, a := range g {23 slices.Sort(a)24 m := len(a)25 s := 026 for i := m - 2; i >= 0; i -= 2 {27 s += a[i+1] - a[i]28 }29 if m%2 == 0 {30 ans += s31 continue32 }33 34 if odd {35 ans = -136 break37 }38 odd = true39 40 minS := s41 for i := 1; i < m; i += 2 {42 s += a[i] - a[i-1] - (a[i+1] - a[i])43 minS = min(minS, s)44 }45 ans += minS46 }47 Fprintln(out, ans)48 }49}50 5152