- 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
- 57 lines of Go from the credited upstream file 474F.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.
Use this to learn the idea, then write your own version.
1package main2 3import (4 "bufio"5 . "fmt"6 "io"7 "math/bits"8 "sort"9)10 1112type st74 [][17]int13 14func newST74(a []int) st74 {15 n := len(a)16 st := make(st74, n)17 for i, v := range a {18 st[i][0] = v19 }20 for j := 1; 1<<j <= n; j++ {21 for i := 0; i+1<<j <= n; i++ {22 st[i][j] = gcd74(st[i][j-1], st[i+1<<(j-1)][j-1])23 }24 }25 return st26}27 28func (st st74) query(l, r int) int {29 k := bits.Len(uint(r-l)) - 130 return gcd74(st[l][k], st[r-1<<k][k])31}32 33func cf474F(in io.Reader, _w io.Writer) {34 out := bufio.NewWriter(_w)35 defer out.Flush()36 var n, q, l, r int37 Fscan(in, &n)38 a := make([]int, n)39 pos := map[int][]int{}40 for i := range a {41 Fscan(in, &a[i])42 pos[a[i]] = append(pos[a[i]], i)43 }44 45 t := newST74(a)46 Fscan(in, &q)47 for range q {48 Fscan(in, &l, &r)49 l--50 p := pos[t.query(l, r)]51 Fprintln(out, r-l-sort.SearchInts(p, r)+sort.SearchInts(p, l))52 }53}54 5556func gcd74(a, b int) int { for a != 0 { a, b = b%a, a }; return b }57