Approach
Depth-first search
For Codeforces 1615E — Purple Crayon, 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
- 66 lines of Go from the credited upstream file 1615E.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 "slices"8)9 1011func cf1615E(in io.Reader, _w io.Writer) {12 out := bufio.NewWriter(_w)13 defer out.Flush()14 var n, k int15 Fscan(in, &n, &k)16 g := make([][]int, n)17 for range n - 1 {18 var v, w int19 Fscan(in, &v, &w)20 v--21 w--22 g[v] = append(g[v], w)23 g[w] = append(g[w], v)24 }25 26 ls := []int{}27 var dfs func(int, int) int28 dfs = func(v, fa int) int {29 maxL := 030 for _, w := range g[v] {31 if w == fa {32 continue33 }34 l := dfs(w, v)35 if maxL > 0 {36 ls = append(ls, min(maxL, l))37 }38 maxL = max(maxL, l)39 }40 return maxL + 141 }42 ls = append(ls, dfs(0, -1))43 44 maxR := len(ls)45 if maxR <= k {46 47 48 r := maxR 49 if n/2 >= maxR {50 r = min(k, n/2)51 }52 Fprint(out, (n-r)*r)53 return54 }55 56 slices.Sort(ls)57 b := n58 for _, v := range ls[maxR-k:] {59 b -= v60 }61 b = min(b, n/2)62 Fprint(out, (n-k-b)*(k-b))63}64 6566