Problem solution · Go

Codeforces 1146F — Leaf Partition

Codeforces 1146F — Leaf Partition: a Go solution using direct simulation. Learn the idea, check the complexity, and read the full code, with credit to EndlessCheng Codeforces Go.

Technique
Direct simulation
Source
EndlessCheng Codeforces Go
Length
41 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

Direct simulation

For Codeforces 1146F — Leaf Partition, the implementation follows the problem’s operations directly while maintaining only the state needed for the next decision.

  1. Translate each rule into one explicit state update.
  2. Maintain the invariant after every processed item.
  3. Return the accumulated state once all relevant input has been handled.

Code notes

  • 41 lines of Go from the credited upstream file 1146F.go.
  • The implementation visibly relies on sequence storage.
  • No explicit loop blocks detected.

Complexity

Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.

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 1146F — Leaf Partition · GoGo
Use this to learn the idea, then write your own version.
package main import (	. "fmt"	"io") // https://github.com/EndlessChengfunc cf1146F(in io.Reader, out io.Writer) {	const mod = 998244353	var n, p int	Fscan(in, &n)	g := make([][]int, n)	for w := 1; w < n; w++ {		Fscan(in, &p)		g[p-1] = append(g[p-1], w)	} 	// 0: 子树中没有路径延伸到 v	// 1: 子树中恰好有一条路径延伸到 v	// 2: 子树中有 >= 两条路径在 v 处合并,或者 v 本身就是一个叶子	f := make([][3]int, n)	for v := n - 1; v >= 0; v-- {		if g[v] == nil {			f[v][2] = 1			continue		}		f[v][0] = 1		for _, w := range g[v] {			zero := f[w][0] + f[w][2]			one := f[w][1] + f[w][2]			f[v][2] = (f[v][2]*(zero+one) + f[v][1]*one) % mod			f[v][1] = (f[v][1]*zero + f[v][0]*one) % mod			f[v][0] = f[v][0] * zero % mod		}	}	Fprint(out, (f[0][0]+f[0][2])%mod)} //func main() { cf1146F(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 ↗