- 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
- 83 lines of Go from the credited upstream file 429D.go.
- The implementation visibly relies on sequence storage.
- 1 loop block 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 "math"8)9 1011type vec29 struct{ x, y int64 }12 13func merge29(a, b []vec29) []vec29 {14 i, n := 0, len(a)15 j, m := 0, len(b)16 res := make([]vec29, 0, n+m)17 for {18 if i == n {19 return append(res, b[j:]...)20 }21 if j == m {22 return append(res, a[i:]...)23 }24 if a[i].y < b[j].y {25 res = append(res, a[i])26 i++27 } else {28 res = append(res, b[j])29 j++30 }31 }32}33 34func closestPair(ps []vec29) int64 {35 n := len(ps)36 if n <= 1 {37 return math.MaxInt6438 }39 m := n >> 140 x := ps[m].x41 d2 := min29(closestPair(ps[:m]), closestPair(ps[m:]))42 copy(ps, merge29(ps[:m], ps[m:]))43 checkPs := []vec29{}44 for _, pi := range ps {45 if (pi.x-x)*(pi.x-x) > d2 {46 continue47 }48 for j := len(checkPs) - 1; j >= 0; j-- {49 pj := checkPs[j]50 dy := pi.y - pj.y51 if dy*dy >= d2 {52 break53 }54 dx := pi.x - pj.x55 d2 = min29(d2, dx*dx+dy*dy)56 }57 checkPs = append(checkPs, pi)58 }59 return d260}61 62func CF429D(_r io.Reader, out io.Writer) {63 in := bufio.NewReader(_r)64 var n, v, s int65 Fscan(in, &n)66 ps := make([]vec29, n)67 for i := range ps {68 Fscan(in, &v)69 s += v70 ps[i] = vec29{int64(i), int64(s)}71 }72 Fprint(out, closestPair(ps))73}74 75func min29(a, b int64) int64 {76 if a < b {77 return a78 }79 return b80}81 8283