- 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
- 65 lines of Go from the credited upstream file 864E.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 CF864E(_r io.Reader, _w io.Writer) {12 in := bufio.NewReader(_r)13 out := bufio.NewWriter(_w)14 defer out.Flush()15 type pair struct{ w, mxW, v, i int }16 17 var n int18 Fscan(in, &n)19 a := make([]pair, n)20 for i := range a {21 Fscan(in, &a[i].w, &a[i].mxW, &a[i].v)22 a[i].i = i + 123 }24 sort.Slice(a, func(i, j int) bool { return a[i].mxW < a[j].mxW })25 26 m := a[n-1].mxW27 dp := make([]int, m)28 fa := make([][]int, n)29 for i := range fa {30 fa[i] = make([]int, m)31 for j := range fa[i] {32 fa[i][j] = -133 }34 }35 for i, p := range a {36 w := p.w37 for j := p.mxW - 1; j >= w; j-- {38 if d := dp[j-w] + p.v; d > dp[j] {39 dp[j] = d40 fa[i][j] = j - w41 }42 }43 }44 mxJ := 045 for j, v := range dp {46 if v > dp[mxJ] {47 mxJ = j48 }49 }50 Fprintln(out, dp[mxJ]) 51 ans := []int{}52 for i, j := n-1, mxJ; i >= 0; i-- {53 if fa[i][j] != -1 {54 ans = append(ans, a[i].i)55 j = fa[i][j]56 }57 }58 Fprintln(out, len(ans))59 for i := len(ans) - 1; i >= 0; i-- {60 Fprint(out, ans[i], " ")61 }62}63 6465