- 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
- 94 lines of Go from the credited upstream file 1354E.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 "bytes"6 . "fmt"7 "io"8)9 1011func CF1354E(_r io.Reader, out io.Writer) {12 in := bufio.NewReader(_r)13 var n, m, n1, n2, n3, v, w int14 Fscan(in, &n, &m, &n1, &n2, &n3)15 g := make([][]int, n)16 for ; m > 0; m-- {17 Fscan(in, &v, &w)18 v--19 w--20 g[v] = append(g[v], w)21 g[w] = append(g[w], v)22 }23 24 color := make([]int8, n)25 cnt := [2]int{}26 vs := []int{}27 var f func(int, int8) bool28 f = func(v int, c int8) bool {29 color[v] = c30 cnt[c-1]++31 vs = append(vs, v)32 for _, w := range g[v] {33 if color[w] == c || color[w] == 0 && !f(w, 3^c) {34 return false35 }36 }37 return true38 }39 dp := make([]bool, n2+1) 40 dp[0] = true41 from := make([][]int, n)42 for i := range from {43 from[i] = make([]int, n2+1)44 }45 cc := [][]int{}46 for i, c := range color {47 if c != 0 {48 continue49 }50 cnt = [2]int{}51 vs = []int{}52 if !f(i, 1) {53 Fprint(out, "NO")54 return55 }56 o:57 for j := n2; j >= 0; j-- { 58 for k, c := range cnt {59 if c <= j && dp[j-c] {60 dp[j] = true61 from[len(cc)][j] = (j-c)<<1 | k62 continue o63 }64 }65 dp[j] = false 66 }67 cc = append(cc, vs)68 }69 70 if !dp[n2] {71 Fprint(out, "NO")72 return73 }74 Fprintln(out, "YES")75 ans := bytes.Repeat([]byte{'3'}, n)76 for i, j := len(cc)-1, n2; i >= 0; i-- {77 j = from[i][j]78 tar := int8(j&1) + 179 j >>= 180 for _, v := range cc[i] {81 if color[v] == tar {82 n2--83 ans[v] = '2'84 } else if n1 > 0 {85 n1--86 ans[v] = '1'87 }88 }89 }90 Fprintf(out, "%s", ans)91}92 9394