- 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
- 90 lines of Go from the credited upstream file 506D.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 "slices"8)9 1011type uf06 map[int32]int3212 13func (u uf06) find(x int32) int32 {14 fx, ok := u[x]15 if !ok {16 u[x] = x17 fx = x18 }19 if fx != x {20 u[x] = u.find(fx)21 return u[x]22 }23 return x24}25 26func (u uf06) merge(x, y int32) {27 u[u.find(x)] = u.find(y)28}29 30func (u uf06) same(x, y int32) bool {31 return u.find(x) == u.find(y)32}33 34func cf506D(_r io.Reader, _w io.Writer) {35 in := bufio.NewReader(_r)36 out := bufio.NewWriter(_w)37 defer out.Flush()38 39 var n, m, v, w, c, q int3240 Fscan(in, &n, &m)41 us := make([]uf06, m+1)42 for i := range us {43 us[i] = uf06{}44 }45 cs := make([][]int32, n+1)46 for ; m > 0; m-- {47 Fscan(in, &v, &w, &c)48 cs[v] = append(cs[v], c)49 cs[w] = append(cs[w], c)50 us[c].merge(v, w)51 }52 for _, u := range us {53 for v := range u {54 u.find(v)55 }56 }57 for i, a := range cs {58 if a != nil {59 slices.Sort(a)60 cs[i] = slices.Compact(a)61 }62 }63 64 Fscan(in, &q)65 type pair struct{ v, w int32 }66 memo := make(map[pair]int32, q)67 for ; q > 0; q-- {68 Fscan(in, &v, &w)69 if len(cs[v]) > len(cs[w]) {70 v, w = w, v71 }72 p := pair{v, w}73 if ans, ok := memo[p]; ok {74 Fprintln(out, ans)75 continue76 }77 ans := int32(0)78 for _, c := range cs[v] {79 u := us[c]80 if u[v] == u[w] {81 ans++82 }83 }84 Fprintln(out, ans)85 memo[p] = ans86 }87}88 8990