Problem solution · Go

Codeforces 1467E — Distinctive Roots in a Tree

Codeforces 1467E — Distinctive Roots in a Tree: a Go solution using depth-first search. Learn the idea, check the complexity, and read the full code, with credit to EndlessCheng Codeforces Go.

Technique
Depth-first search
Source
EndlessCheng Codeforces Go
Length
69 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Depth-first search

For Codeforces 1467E — Distinctive Roots in a Tree, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.

  1. Define the state carried into one recursive or stack frame.
  2. Mark or choose the current state before exploring children.
  3. Combine child results or undo the choice when the branch finishes.

Code notes

  • 69 lines of Go from the credited upstream file 1467E.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.

Source

Code and credit

This code comes from EndlessCheng Codeforces Go by Σndless (EndlessCheng) and is used under the MIT licence.

Full codeCodeforces 1467E — Distinctive Roots in a Tree · GoGo
Use this to learn the idea, then write your own version.
package main import (	. "fmt"	"io") // https://github.com/EndlessChengfunc cf1467E(in io.Reader, out io.Writer) {	var n, ts, s, ans int	Fscan(in, &n)	a := make([]int, n)	tot := map[int]int{}	for i := range a {		Fscan(in, &a[i])		tot[a[i]]++	}	g := make([][]int, n)	for range n - 1 {		var v, w int		Fscan(in, &v, &w)		v--		w--		g[v] = append(g[v], w)		g[w] = append(g[w], v)	} 	d := make([]int, n+1)	inT := make([]int, n)	cnt := map[int]int{}	var dfs func(int, int)	dfs = func(v, fa int) {		inT[v] = ts		ts++		color := a[v]		c0 := cnt[color]		cnt[color]++		for _, w := range g[v] {			if w == fa {				continue			}			c := cnt[color]			dfs(w, v)			if cnt[color] > c { // 说明 w 中有 color,那么另一侧 v(除去 w)是坏的				// 除去子树 w 的其余点 +1(注意这不含 w)				d[0]++				d[inT[w]]--				d[ts]++			}		}		// 说明子树 v 是坏的		if cnt[color]-c0 < tot[color] {			d[inT[v]]++			d[ts]--		}	}	dfs(0, -1) 	for _, v := range d[:n] {		s += v		if s == 0 {			ans++		}	}	Fprint(out, ans)} //func main() { cf1467E(bufio.NewReader(os.Stdin), os.Stdout) } 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗