- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 74 lines of Go from the credited upstream file 427C.go.
- The implementation visibly relies on sequence storage.
- 1 loop block 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.
Use this to learn the idea, then write your own version.
1package main2 3import (4 "bufio"5 . "fmt"6 "io"7)8 910func CF427C(_r io.Reader, out io.Writer) {11 in := bufio.NewReader(_r)12 const mod = 1_000_000_00713 var n, m, v, w int14 Fscan(in, &n)15 a := make([]int, n)16 for i := range a {17 Fscan(in, &a[i])18 }19 g := make([][]int, n)20 for Fscan(in, &m); m > 0; m-- {21 Fscan(in, &v, &w)22 g[v-1] = append(g[v-1], w-1)23 }24 25 sum, ways := int64(0), int64(1)26 dfn := make([]int, n)27 clock := 028 stk := []int{}29 inStk := make([]bool, n)30 var f func(int) int31 f = func(v int) int {32 clock++33 dfn[v] = clock34 lowV := clock35 stk = append(stk, v)36 inStk[v] = true37 for _, w := range g[v] {38 if dfn[w] == 0 {39 lowW := f(w)40 lowV = min(lowV, lowW)41 } else if inStk[w] {42 lowV = min(lowV, dfn[w])43 }44 }45 if dfn[v] == lowV {46 mn, cnt := int(1e9), 047 for {48 w := stk[len(stk)-1]49 stk = stk[:len(stk)-1]50 inStk[w] = false51 if a[w] < mn {52 mn, cnt = a[w], 153 } else if a[w] == mn {54 cnt++55 }56 if w == v {57 break58 }59 }60 sum += int64(mn)61 ways = ways * int64(cnt) % mod62 }63 return lowV64 }65 for i, ts := range dfn {66 if ts == 0 {67 f(i)68 }69 }70 Fprint(out, sum, ways)71}72 7374