- 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
- 79 lines of Go from the credited upstream file 2005D.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)8 910func cf2005D(in io.Reader, _w io.Writer) {11 out := bufio.NewWriter(_w)12 defer out.Flush()13 gcd := func(a, b int) int {14 for a != 0 {15 a, b = b%a, a16 }17 return b18 }19 20 var T, n int21 for Fscan(in, &T); T > 0; T-- {22 Fscan(in, &n)23 type pair struct{ x, y int }24 a := make([]pair, n)25 for i := range a {26 Fscan(in, &a[i].x)27 }28 for i := range a {29 Fscan(in, &a[i].y)30 }31 32 suf := make([]pair, n+1)33 for i := n - 1; i >= 0; i-- {34 suf[i].x = gcd(suf[i+1].x, a[i].x)35 suf[i].y = gcd(suf[i+1].y, a[i].y)36 }37 38 mx, cnt := 0, 039 type result struct{ g1, g2, l int }40 res := []result{}41 pre := pair{}42 for i, v := range a {43 for j, p := range res {44 res[j].g1 = gcd(p.g1, v.y)45 res[j].g2 = gcd(p.g2, v.x)46 }47 res = append(res, result{gcd(pre.x, v.y), gcd(pre.y, v.x), i})48 49 j := 150 for k := 1; k < len(res); k++ {51 if res[k].g1 != res[k-1].g1 || res[k].g2 != res[k-1].g2 {52 res[j] = res[k]53 j++54 }55 }56 res = res[:j]57 58 prePos := i + 159 for k := len(res) - 1; k >= 0; k-- {60 p := res[k]61 s := gcd(p.g1, suf[i+1].x) + gcd(p.g2, suf[i+1].y)62 if s > mx {63 mx = s64 cnt = prePos - p.l65 } else if s == mx {66 cnt += prePos - p.l67 }68 prePos = p.l69 }70 71 pre.x = gcd(pre.x, v.x)72 pre.y = gcd(pre.y, v.y)73 }74 Fprintln(out, mx, cnt)75 }76}77 7879