- 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
- 67 lines of Go from the credited upstream file 1500B.go.
- The implementation visibly relies on sequence storage.
- 1 loop block 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 CF1500B(_r io.Reader, out io.Writer) {11 in := bufio.NewReader(_r)12 max := func(a, b int) int {13 if a > b {14 return a15 }16 return b17 }18 19 var n, m, loop int20 var k, cntDiff int6421 Fscan(in, &n, &m, &k)22 a := make([]int, n)23 pos := make([]int, max(n, m)*2+1)24 for i := range pos {25 pos[i] = -126 }27 diff := make([]int, n)28 for i := range a {29 Fscan(in, &a[i])30 pos[a[i]] = i31 diff[i] = m32 }33 b := make([]int, m)34 for i := range b {35 Fscan(in, &b[i])36 if pos[b[i]] >= 0 {37 diff[((pos[b[i]]-i)%n+n)%n]--38 }39 }40 41 i := 042 for {43 cntDiff += int64(diff[i])44 loop++45 i = (i + m) % n46 if i == 0 {47 break48 }49 }50 ans := (k - 1) / cntDiff * int64(loop) * int64(m)51 k -= (k - 1) / cntDiff * cntDiff52 for ; k > int64(diff[i]); i = (i + m) % n {53 k -= int64(diff[i])54 ans += int64(m)55 }56 for j := 0; k > 0; j++ {57 if a[i] != b[j] {58 k--59 }60 ans++61 i = (i + 1) % n62 }63 Fprint(out, ans)64}65 6667