- 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
- 73 lines of Go from the credited upstream file 1292C.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 CF1292C(_r io.Reader, out io.Writer) {11 in := bufio.NewReader(_r)12 max := func(a, b int64) int64 {13 if b > a {14 return b15 }16 return a17 }18 19 var n, v, w int20 Fscan(in, &n)21 g := make([][]int, n)22 for i := 1; i < n; i++ {23 Fscan(in, &v, &w)24 v--25 w--26 g[v] = append(g[v], w)27 g[w] = append(g[w], v)28 }29 30 pa := make([][]int, n)31 sz := make([][]int, n)32 for i := range pa {33 pa[i] = make([]int, n)34 sz[i] = make([]int, n)35 var f func(int, int)36 f = func(v, fa int) {37 pa[i][v] = fa38 sz[i][v] = 139 for _, w := range g[v] {40 if w != fa {41 f(w, v)42 sz[i][v] += sz[i][w]43 }44 }45 }46 f(i, -1)47 }48 49 dp := make([][]int64, n)50 for i := range dp {51 dp[i] = make([]int64, n)52 }53 var f func(int, int) int6454 f = func(v, w int) int64 {55 if v == w {56 return 057 }58 if dp[v][w] == 0 {59 dp[v][w] = max(f(pa[w][v], w), f(v, pa[v][w])) + int64(sz[v][w]*sz[w][v])60 }61 return dp[v][w]62 }63 ans := int64(0)64 for v := 0; v < n; v++ {65 for w := v + 1; w < n; w++ {66 ans = max(ans, f(v, w))67 }68 }69 Fprint(out, ans)70}71 7273