- 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
- 93 lines of Go from the credited upstream file 1771D.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 CF1771D(_r io.Reader, _w io.Writer) {11 in := bufio.NewReader(_r)12 out := bufio.NewWriter(_w)13 defer out.Flush()14 max := func(a, b int) int {15 if b > a {16 return b17 }18 return a19 }20 21 var T, n, v, w int22 var s []byte23 for Fscan(in, &T); T > 0; T-- {24 Fscan(in, &n, &s)25 g := make([][]int, n)26 for i := 1; i < n; i++ {27 Fscan(in, &v, &w)28 v--29 w--30 g[v] = append(g[v], w)31 g[w] = append(g[w], v)32 }33 34 move1 := make([][]int, n)35 for i := range move1 {36 move1[i] = make([]int, n)37 }38 for rt := range move1 {39 var build func(int, int)40 build = func(v, fa int) {41 move1[v][rt] = fa42 for _, w := range g[v] {43 if w != fa {44 build(w, v)45 }46 }47 }48 build(rt, rt)49 }50 51 dp := make([][]int, n)52 for i := range dp {53 dp[i] = make([]int, n)54 for j := range dp[i] {55 dp[i][j] = -156 }57 }58 var f func(int, int) int59 f = func(v, w int) (res int) {60 if v > w { 61 v, w = w, v62 }63 if v == w {64 return 165 }66 if move1[v][w] == w {67 if s[v] == s[w] {68 return 269 }70 return 171 }72 dv := &dp[v][w]73 if *dv != -1 {74 return *dv75 }76 defer func() { *dv = res }()77 if s[v] == s[w] {78 return 2 + f(move1[v][w], move1[w][v])79 }80 return max(f(move1[v][w], w), f(v, move1[w][v]))81 }82 ans := 083 for i := 0; i < n; i++ {84 for j := i; j < n; j++ {85 ans = max(ans, f(i, j))86 }87 }88 Fprintln(out, ans)89 }90}91 9293