Approach
Depth-first search
For Codeforces 107D — Crime Management, 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
- 124 lines of Go from the credited upstream file 107D.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 . "fmt"5 "io"6)7 89const mod7 = 1234510 11type matrix7 [][]int12 13func newMatrix7(n, m int) matrix7 {14 a := make(matrix7, n)15 for i := range a {16 a[i] = make([]int, m)17 }18 return a19}20 21func (a matrix7) mul(b matrix7) matrix7 {22 c := newMatrix7(len(a), len(b[0]))23 for i, row := range a {24 for k, x := range row {25 if x == 0 {26 continue27 }28 for j, y := range b[k] {29 c[i][j] = (c[i][j] + x*y) % mod730 }31 }32 }33 return c34}35 36func (a matrix7) powMul(n int, f0 matrix7) matrix7 {37 res := f038 for ; n > 0; n /= 2 {39 if n%2 > 0 {40 res = a.mul(res)41 }42 a = a.mul(a)43 }44 return res45}46 47func cf107D(in io.Reader, out io.Writer) {48 gcd := func(a, b int) int {49 for a != 0 {50 a, b = b%a, a51 }52 return b53 }54 lcm := func(a, b int) int { return a / gcd(a, b) * b }55 56 var n, k, v, ans int57 var s string58 Fscan(in, &n, &k)59 g := [26][]int{}60 lcms := [26]int{}61 for i := range lcms {62 lcms[i] = 163 }64 for range k {65 Fscan(in, &s, &v)66 b := s[0] - 'A'67 g[b] = append(g[b], v)68 lcms[b] = lcm(lcms[b], v)69 }70 71 size := 172 for _, l := range lcms {73 size *= l74 }75 76 m := newMatrix7(size, size)77 var dfs func(int, int, int, bool)78 dfs = func(i, new, old int, ch bool) {79 if i < 0 {80 if ch {81 m[new][old]++82 }83 return84 }85 if g[i] == nil {86 dfs(i-1, new, old, ch)87 return88 }89 l := lcms[i]90 for j := range l {91 dfs(i-1, new*l+j, old*l+j, ch)92 if !ch {93 dfs(i-1, new*l+(j+1)%l, old*l+j, true)94 }95 }96 }97 dfs(25, 0, 0, false)98 99 f0 := newMatrix7(size, 1)100 f0[0][0] = 1101 fn := m.powMul(n, f0)102nxt:103 for mask, row := range fn {104 for i, a := range g {105 if a == nil {106 continue107 }108 c := mask % lcms[i]109 for _, v := range a {110 if c%v == 0 {111 goto ok112 }113 }114 continue nxt115 ok:116 mask /= lcms[i]117 }118 ans += row[0]119 }120 Fprint(out, ans%mod7)121}122 123124