Approach
Depth-first search
For Codeforces 601D — Acyclic Organic Compounds, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 71 lines of Go from the credited upstream file 601D.go.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
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 . "fmt"5 "io"6)7 89func cf601D(in io.Reader, out io.Writer) {10 var n int11 var s string12 Fscan(in, &n)13 c := make([]int, n+1)14 for i := 1; i <= n; i++ {15 Fscan(in, &c[i])16 }17 Fscan(in, &s)18 s = " " + s19 g := make([][]int, n+1)20 for range n - 1 {21 var v, w int22 Fscan(in, &v, &w)23 g[v] = append(g[v], w)24 g[w] = append(g[w], v)25 }26 27 ch := make([][26]int, n+1)28 f := make([]int, n+1)29 var merge func(int, int) int30 merge = func(x, y int) int {31 if x == 0 || y == 0 {32 if x != 0 {33 return x34 }35 return y36 }37 f[x] = 138 for i := range 26 {39 ch[x][i] = merge(ch[x][i], ch[y][i])40 f[x] += f[ch[x][i]]41 }42 return x43 }44 45 ans, cnt := 0, 046 var dfs func(int, int)47 dfs = func(v, fa int) {48 for _, w := range g[v] {49 if w != fa {50 dfs(w, v)51 ch[v][s[w]-'a'] = merge(ch[v][s[w]-'a'], w)52 }53 }54 f[v] = 155 for i := range 26 {56 f[v] += f[ch[v][i]]57 }58 res := f[v] + c[v]59 if res > ans {60 ans, cnt = res, 161 } else if res == ans {62 cnt++63 }64 }65 dfs(1, 0)66 Fprintln(out, ans)67 Fprint(out, cnt)68}69 7071