- 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
- 82 lines of Go from the credited upstream file 1515G.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 cf1515G(in io.Reader, _w io.Writer) {11 gcd := func(a, b int) int {12 for a != 0 {13 a, b = b%a, a14 }15 return b16 }17 out := bufio.NewWriter(_w)18 defer out.Flush()19 var n, m, now, q int20 Fscan(in, &n, &m)21 type nb struct{ to, wt int }22 g := make([][]nb, n)23 for range m {24 var v, w, wt int25 Fscan(in, &v, &w, &wt)26 g[v-1] = append(g[v-1], nb{w - 1, wt})27 }28 29 sccGCD := make([]int, n)30 dis := make([]int, n)31 dfn := make([]int, n)32 st := []int{}33 var tarjan func(int) int34 tarjan = func(v int) int {35 now++36 dfn[v] = now37 lowV := now38 st = append(st, v)39 for _, e := range g[v] {40 w := e.to41 if dfn[w] == 0 {42 dis[w] = dis[v] + e.wt43 lowV = min(lowV, tarjan(w))44 }45 if dfn[w] != 1e9 {46 sccGCD[v] = gcd(gcd(sccGCD[v], sccGCD[w]), dis[v]-dis[w]+e.wt)47 lowV = min(lowV, dfn[w])48 }49 }50 if dfn[v] == lowV {51 for {52 w := st[len(st)-1]53 st = st[:len(st)-1]54 sccGCD[w] = sccGCD[v]55 dfn[w] = 1e956 if w == v {57 break58 }59 }60 }61 return lowV62 }63 for i, t := range dfn {64 if t == 0 {65 tarjan(i)66 }67 }68 69 Fscan(in, &q)70 for range q {71 var v, s, t int72 Fscan(in, &v, &s, &t)73 if s%gcd(sccGCD[v-1], t) == 0 {74 Fprintln(out, "YES")75 } else {76 Fprintln(out, "NO")77 }78 }79}80 8182