- Define precisely what one DP state represents.
- Establish the base cases before transitions are evaluated.
- Process states in dependency order and combine only already-known values.
Code notes
- 69 lines of Go from the credited upstream file 1637D.go.
- The implementation visibly relies on sequence storage, cached states.
- No explicit loop blocks detected.
Complexity
Multiply the number of reachable states by the work performed for each transition, then include the stored state table in memory usage.
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)8 910func CF1637D(_r io.Reader, _w io.Writer) {11 in := bufio.NewReader(_r)12 out := bufio.NewWriter(_w)13 defer out.Flush()14 abs := func(x int) int {15 if x < 0 {16 return -x17 }18 return x19 }20 21 var T, n int22 for Fscan(in, &T); T > 0; T-- {23 Fscan(in, &n)24 ans, maxW := 0, 025 a := make([][2]int, n)26 for i := range a {27 Fscan(in, &a[i][0])28 ans += a[i][0] * a[i][0]29 maxW += a[i][0]30 }31 for i := range a {32 Fscan(in, &a[i][1])33 ans += a[i][1] * a[i][1]34 maxW += a[i][1]35 }36 if n == 1 {37 Fprintln(out, 0)38 continue39 }40 dp := make([]bool, maxW+1)41 dp[0] = true42 for _, g := range a {43 next:44 for j := maxW; j >= 0; j-- {45 for _, w := range g {46 if w <= j && dp[j-w] {47 dp[j] = true48 continue next49 }50 }51 dp[j] = false52 }53 }54 ans *= n - 255 mi, miv := int(1e9), 056 for v, b := range dp {57 if b {58 d := abs(maxW - 2*v)59 if d < mi {60 mi, miv = d, v61 }62 }63 }64 Fprintln(out, ans+miv*miv+(maxW-miv)*(maxW-miv))65 }66}67 6869