- 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
- 112 lines of Go from the credited upstream file 1165D.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 "sort"8)9 1011 1213 14func CF1165D(_r io.Reader, _w io.Writer) {15 in := bufio.NewReader(_r)16 out := bufio.NewWriter(_w)17 defer out.Flush()18 const mx int = 1e619 lpf := [mx + 1]int{1: 1}20 for i := 2; i <= mx; i++ {21 if lpf[i] == 0 {22 for j := i; j <= mx; j += i {23 if lpf[j] == 0 {24 lpf[j] = i25 }26 }27 }28 }29 divisors := func(n int64, a []int) bool {30 ds := []int{}31 for d := int64(2); d*d <= n; d++ {32 if n%d == 0 {33 if d > 1e6 {34 return false35 }36 ds = append(ds, int(d))37 if d*d < n {38 if n/d > 1e6 {39 return false40 }41 ds = append(ds, int(n/d))42 }43 if len(ds) > len(a) {44 return false45 }46 }47 }48 if len(ds) < len(a) {49 return false50 }51 sort.Ints(ds)52 sort.Ints(a)53 for i, v := range ds {54 if v != a[i] {55 return false56 }57 }58 return true59 }60 61 var t, n int62o:63 for Fscan(in, &t); t > 0; t-- {64 ps := map[int]int8{}65 minP := int(1e9)66 Fscan(in, &n)67 a := make([]int, n)68 for i := range a {69 Fscan(in, &a[i])70 for v := a[i]; v > 1; {71 p := lpf[v]72 e := int8(1)73 for v /= p; lpf[v] == p; v /= p {74 e++75 }76 if e > ps[p] {77 ps[p] = e78 }79 if p < minP {80 minP = p81 }82 }83 }84 ans := int64(1)85 for p, e := range ps {86 for ; e > 0; e-- {87 ans *= int64(p)88 if ans > 1e12 {89 Fprintln(out, -1)90 continue o91 }92 }93 }94 for _, v := range a {95 if int64(v) == ans {96 ans *= int64(minP)97 if ans > 1e12 {98 Fprintln(out, -1)99 continue o100 }101 break102 }103 }104 if !divisors(ans, a) {105 ans = -1106 }107 Fprintln(out, ans)108 }109}110 111112