- 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
- 58 lines of Go from the credited upstream file 1575M.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 . "fmt"5 "io"6)7 89type vec75 struct{ x, y int }10func (a vec75) sub(b vec75) vec75 { return vec75{a.x - b.x, a.y - b.y} }11func (a vec75) dot(b vec75) int { return a.x*b.x + a.y*b.y }12func (a vec75) det(b vec75) int { return a.x*b.y - a.y*b.x }13 14func cf1575M(in io.Reader, out io.Writer) {15 var n, m, ans int16 var s []byte17 Fscan(in, &n, &m)18 n++19 m++20 pos := make([][]int, n)21 for i := range n {22 Fscan(in, &s)23 for j, b := range s {24 if b == '1' {25 pos[i] = append(pos[i], j)26 }27 }28 }29 30 for y := range m {31 q := []vec75{}32 for x, ys := range pos {33 if ys == nil {34 continue35 }36 if len(ys) > 1 && ys[1]-y < y-ys[0] {37 ys = ys[1:]38 pos[x] = ys39 }40 p := vec75{x, x*x - y*ys[0]*2 + ys[0]*ys[0]}41 for len(q) > 1 && q[len(q)-1].sub(q[len(q)-2]).det(p.sub(q[len(q)-1])) <= 0 {42 q = q[:len(q)-1]43 }44 q = append(q, p)45 }46 for x := range n {47 p := vec75{-x * 2, 1}48 for len(q) > 1 && p.dot(q[0]) >= p.dot(q[1]) {49 q = q[1:]50 }51 ans += p.dot(q[0]) + x*x + y*y52 }53 }54 Fprint(out, ans)55}56 5758