Approach
Depth-first search
For Codeforces 1778F — Maximizing Root, 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
- 122 lines of Go from the credited upstream file 1778F.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 "bufio"5 . "fmt"6 "io"7)8 9func cf1778F(in io.Reader, _w io.Writer) {10 out := bufio.NewWriter(_w)11 defer out.Flush()12 const mx = 100013 divisors := [mx + 1][]int{}14 for i := mx; i > 0; i-- {15 for j := i; j <= mx; j += i {16 divisors[j] = append(divisors[j], i)17 }18 }19 lpf := [mx + 1]int{1: 1}20 for i := 2; i <= mx; i++ {21 if lpf[i] == 0 {22 for j := i; j <= mx; j += i {23 if lpf[j] == 0 {24 lpf[j] = i25 }26 }27 }28 }29 ceilSqrt := [mx + 1]int{}30 calcCeilSqrt := func(x int) int {31 res := 132 for x > 1 {33 p := lpf[x]34 for p2 := p * p; x%p2 == 0; x /= p2 {35 res *= p36 }37 if x%p == 0 {38 res *= p39 x /= p40 }41 }42 return res43 }44 for i := 1; i <= mx; i++ {45 ceilSqrt[i] = calcCeilSqrt(i)46 }47 gcd := func(a, b int) int {48 for a != 0 {49 a, b = b%a, a50 }51 return b52 }53 54 var T, n, k int55 for Fscan(in, &T); T > 0; T-- {56 Fscan(in, &n, &k)57 a := make([]int, n)58 for i := range a {59 Fscan(in, &a[i])60 }61 g := make([][]int, n)62 for i := 1; i < n; i++ {63 var v, w int64 Fscan(in, &v, &w)65 v--66 w--67 g[v] = append(g[v], w)68 g[w] = append(g[w], v)69 }70 if k == 0 {71 Fprintln(out, a[0])72 continue73 }74 75 subGcd := make([]int, n)76 var dfs0 func(int, int)77 dfs0 = func(v, fa int) {78 subGcd[v] = a[v]79 for _, w := range g[v] {80 if w != fa {81 dfs0(w, v)82 subGcd[v] = gcd(subGcd[v], subGcd[w])83 }84 }85 }86 dfs0(0, -1)87 88 var dfs func(int, int, int) int89 dfs = func(v, fa, targetGcd int) int {90 if subGcd[v]%targetGcd == 0 {91 return 092 }93 if subGcd[v]*subGcd[v]%targetGcd == 0 {94 return 195 }96 if a[v]*a[v]%targetGcd > 0 {97 return 1e998 }99 cnt := 1100 for _, w := range g[v] {101 if w != fa {102 cnt += dfs(w, v, ceilSqrt[targetGcd])103 }104 }105 return cnt106 }107 108 for _, d := range divisors[a[0]] {109 cnt := 0110 for _, v := range g[0] {111 cnt += dfs(v, 0, d)112 }113 if cnt < k {114 Fprintln(out, a[0]*d)115 break116 }117 }118 }119}120 121122