Problem solution · Go

Codeforces 1770D — Koxia and Game

Codeforces 1770D — Koxia and Game: 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
62 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 1770D — Koxia and Game, 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

  • 62 lines of Go from the credited upstream file 1770D.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 1770D — Koxia and Game · GoGo
Use this to learn the idea, then write your own version.
package main import (	"bufio"	. "fmt"	"io") // https://space.bilibili.com/206214func CF1770D(_r io.Reader, _w io.Writer) {	in := bufio.NewReader(_r)	out := bufio.NewWriter(_w)	defer out.Flush()	const mod = 998244353 	var T, n, w int	for Fscan(in, &T); T > 0; T-- {		Fscan(in, &n)		g := make([][]int, n)		a := make([]int, n)		for i := range a {			Fscan(in, &a[i])		}		for _, v := range a {			v--			Fscan(in, &w)			w--			g[v] = append(g[v], w)			g[w] = append(g[w], v)		} 		vis := make([]bool, n)		c := 0		var dfs func(int, int)		dfs = func(v, fa int) {			vis[v] = true			for _, w := range g[v] {				if w != fa {					if w == v {						c = n					} else if vis[w] {						c = 2					} else {						dfs(w, v)					}				}			}		}		ans := int64(1)		for i, b := range vis {			if !b {				c = 0				dfs(i, -1)				ans = ans * int64(c) % mod			}		}		Fprintln(out, ans)	}} //func main() { CF1770D(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 ↗