- 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
- 73 lines of Go from the credited upstream file 1209E2.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 "sort"8)9 1011func CF1209E2(_r io.Reader, out io.Writer) {12 in := bufio.NewReader(_r)13 max := func(a, b int) int {14 if a > b {15 return a16 }17 return b18 }19 20 var T, n, m int21 for Fscan(in, &T); T > 0; T-- {22 Fscan(in, &n, &m)23 a := make([][]int, m)24 for i := range a {25 a[i] = make([]int, n+1)26 }27 for j := 1; j <= n; j++ {28 for i, r := range a {29 Fscan(in, &r[j])30 a[i][0] = max(a[i][0], r[j])31 }32 }33 sort.Slice(a, func(i, j int) bool { return a[i][0] > a[j][0] })34 if m > n {35 m = n36 a = a[:n]37 }38 39 mx := make([][]int, m)40 for i, r := range a {41 r = r[1:]42 mx[i] = make([]int, 1<<n)43 sum := make([]int, 1<<n)44 for p, v := range r {45 for s := 0; s < 1<<p; s++ {46 t, w := 1<<p|s, sum[s]+v47 sum[t] = w48 for range r {49 mx[i][t] = max(mx[i][t], w)50 t = t<<1&(1<<n-1) | t>>(n-1)51 }52 }53 }54 }55 56 dp := make([][]int, m)57 for i := range dp {58 dp[i] = make([]int, 1<<n)59 }60 dp[0] = mx[0]61 for i := 1; i < m; i++ {62 for s, v := range mx[i] {63 for ss := s; ss < 1<<n; ss = (ss + 1) | s {64 dp[i][ss] = max(dp[i][ss], dp[i-1][ss^s]+v)65 }66 }67 }68 Fprintln(out, dp[m-1][1<<n-1])69 }70}71 7273