Approach
Sorting and greedy selection
For Codeforces 1665C — Tree Infection, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 48 lines of Go from the credited upstream file 1665C.go.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
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 "sort"8)9 1011func CF1665C(_r io.Reader, _w io.Writer) {12 in := bufio.NewReader(_r)13 out := bufio.NewWriter(_w)14 defer out.Flush()15 16 var T, n, v int17 for Fscan(in, &T); T > 0; T-- {18 Fscan(in, &n)19 cnt := make([]int, n)20 for w := 1; w < n; w++ {21 Fscan(in, &v)22 cnt[v-1]++23 }24 25 sort.Sort(sort.Reverse(sort.IntSlice(cnt)))26 low := 127 for _, c := range cnt {28 if c > 0 {29 low++30 }31 }32 ans := low + sort.Search(n-low, func(t int) bool {33 t += low34 need := n - t35 for i, c := range cnt {36 if c <= 1 {37 break38 }39 need -= min(t-1-i, c-1)40 }41 return need <= 042 })43 Fprintln(out, ans)44 }45}46 4748