- 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
- 75 lines of Go from the credited upstream file 891A.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 ST91 [][]int13 14func newST91(a []int) ST91 {15 n := len(a)16 sz := bits.Len(uint(n))17 st := make(ST91, n)18 for i, v := range a {19 st[i] = make([]int, sz)20 st[i][0] = v21 }22 for j := 1; 1<<j <= n; j++ {23 for i := 0; i+1<<j <= n; i++ {24 st[i][j] = gcd91(st[i][j-1], st[i+1<<(j-1)][j-1])25 }26 }27 return st28}29 30func (st ST91) query(l, r int) int {31 k := bits.Len(uint(r-l)) - 132 return gcd91(st[l][k], st[r-1<<k][k])33}34 35func CF891A(_r io.Reader, out io.Writer) {36 in := bufio.NewReader(_r)37 var n, c1 int38 Fscan(in, &n)39 a := make([]int, n)40 for i := range a {41 Fscan(in, &a[i])42 if a[i] == 1 {43 c1++44 }45 }46 if c1 > 0 {47 Fprint(out, n-c1)48 return49 }50 51 st := newST91(a)52 ans := int(1e9)53 for l := range a {54 sz := sort.Search(n-l, func(sz int) bool { return st.query(l, l+sz+1) == 1 })55 56 if sz < n-l && sz < ans {57 ans = sz58 }59 }60 if ans == 1e9 {61 Fprint(out, -1)62 } else {63 Fprint(out, ans+n-1)64 }65}66 6768 69func gcd91(a, b int) int {70 for a != 0 {71 a, b = b%a, a72 }73 return b74}75