- 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
- 72 lines of Go from the credited upstream file 772C.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 CF772C(_r io.Reader, _w io.Writer) {11 in := bufio.NewReader(_r)12 out := bufio.NewWriter(_w)13 defer out.Flush()14 gcd := func(a, b int) int {15 for a != 0 {16 a, b = b%a, a17 }18 return b19 }20 var exgcd func(int, int) (g, x, y int)21 exgcd = func(a, b int) (g, x, y int) {22 if b == 0 {23 return a, 1, 024 }25 g, y, x = exgcd(b, a%b)26 y -= a / b * x27 return28 }29 30 var k, n, v int31 Fscan(in, &k, &n)32 ban := make([]bool, n)33 for ; k > 0; k-- {34 Fscan(in, &v)35 ban[v] = true36 }37 38 gs := make([][]int, n+1)39 for i, b := range ban {40 if !b {41 gs[gcd(i, n)] = append(gs[gcd(i, n)], i) 42 }43 }44 dp := make([]int, n+1)45 from := make([]int, n+1)46 for i := 1; i <= n; i++ {47 dp[i] += len(gs[i])48 for j := i * 2; j <= n; j += i { 49 if dp[i] > dp[j] {50 dp[j] = dp[i]51 from[j] = i52 }53 }54 }55 ans := make([]int, 0, dp[n])56 for i := n; i > 0; i = from[i] {57 for _, v := range gs[i] {58 ans = append(ans, v)59 }60 }61 62 sz := len(ans)63 Fprintln(out, sz)64 Fprint(out, ans[sz-1], " ")65 for i := sz - 1; i > 0; i-- {66 g, x, _ := exgcd(ans[i], n)67 Fprint(out, (int(int64(x)*int64(ans[i-1]/g)%int64(n))+n)%n, " ")68 }69}70 7172