- 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
- 109 lines of Go from the credited upstream file 1147B.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 1011func Sol1147B(reader io.Reader, writer io.Writer) {12 calcMinPeriod := func(pattern []int) int {13 n := len(pattern)14 maxMatchLengths := make([]int, n)15 maxLength := 016 for i := 1; i < n; i++ {17 c := pattern[i]18 for maxLength > 0 && pattern[maxLength] != c {19 maxLength = maxMatchLengths[maxLength-1]20 }21 if pattern[maxLength] == c {22 maxLength++23 }24 maxMatchLengths[i] = maxLength25 }26 if val := maxMatchLengths[n-1]; val > 0 {27 if n%(n-val) == 0 {28 return n / (n - val)29 }30 }31 return 032 }33 calcGCD := func(a, b int64) int64 {34 for b > 0 {35 a, b = b, a%b36 }37 return a38 }39 calcLCM := func(a, b int64) int64 {40 return a / calcGCD(a, b) * b41 }42 43 in := bufio.NewReader(reader)44 out := bufio.NewWriter(writer)45 defer out.Flush()46 47 var n, m int48 Fscan(in, &n, &m)49 lenPosMat := make([][]int, n/2+1)50 for ; m > 0; m-- {51 var a, b int52 Fscan(in, &a, &b)53 if a > b {54 a, b = b, a55 }56 segLen := b - a57 pos := a58 if segLen > n-segLen {59 segLen = n - segLen60 pos = b61 }62 lenPosMat[segLen] = append(lenPosMat[segLen], pos)63 }64 65 k := int64(-1)66 for segLen, posList := range lenPosMat {67 if len(posList) == 0 {68 continue69 }70 var p int71 if segLen*2 < n {72 sort.Ints(posList)73 posList = append(posList, posList[0]+n)74 diffList := make([]int, len(posList)-1)75 for i := range diffList {76 diffList[i] = posList[i+1] - posList[i]77 }78 p = calcMinPeriod(diffList)79 if p == 0 {80 Fprint(out, "No")81 return82 }83 } else if segLen*2 == n {84 p = 285 } else {86 break87 }88 if n%p > 0 {89 Fprint(out, "No")90 return91 }92 p = n / p93 if k == -1 {94 k = int64(p)95 } else {96 k = calcLCM(k, int64(p))97 }98 if k >= int64(n) {99 Fprint(out, "No")100 return101 }102 }103 Fprint(out, "Yes")104}105 106107108109