- 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
- 70 lines of Go from the credited upstream file 623B.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 CF623B(_r io.Reader, out io.Writer) {11 in := bufio.NewReader(_r)12 min := func(a, b int64) int64 {13 if a > b {14 return b15 }16 return a17 }18 19 var n int20 var rm, ch int6421 Fscan(in, &n, &rm, &ch)22 a := make([]int, n)23 for i := range a {24 Fscan(in, &a[i])25 }26 ans := int64(1e18)27 vis := map[int]bool{}28 do := func(p int) {29 if vis[p] {30 return31 }32 vis[p] = true33 dp := [3]int64{}34 35 for _, v := range a {36 cost := int64(0)37 if v%p == 1 || v%p == p-1 {38 cost = ch39 } else if v%p > 0 {40 cost = 1e1841 }42 dp[2] = min(min(dp[1], dp[2])+cost, 1e18)43 dp[1] = min(min(dp[0], dp[1])+rm, 1e18)44 dp[0] = min(dp[0]+cost, 1e18)45 }46 ans = min(ans, min(min(dp[0], dp[1]), dp[2]))47 }48 f := func(x int) {49 for i := 2; i*i <= x; i++ {50 if x%i == 0 {51 for x /= i; x%i == 0; x /= i {52 }53 do(i)54 }55 }56 if x > 1 {57 do(x)58 }59 }60 f(a[0] - 1)61 f(a[0])62 f(a[0] + 1)63 f(a[n-1] - 1)64 f(a[n-1])65 f(a[n-1] + 1)66 Fprint(out, ans)67}68 6970