- 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
- 100 lines of Go from the credited upstream file 1486C2.go.
- The implementation keeps its working state in language-native values and containers.
- 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 . "fmt"5 "os"6)7 8type (9 input86 struct{ n int }10 req86 struct{ l, r int }11 resp86 struct{ v int }12 guess86 struct{ ans int }13)14 1516func CF1486C2(in input86, Q func(req86) resp86) (gs guess86) {17 q := func(l, r int) int { return Q(req86{l, r}).v }18 n := in.n19 ans := 020 defer func() { gs.ans = ans }()21 22 p := q(1, n)23 l, r := 1, n+124 ll, rr := l, r25 for {26 if r-l == 2 {27 ans = l + r - 1 - q(l, r-1)28 return29 }30 31 if r-l == 3 {32 p, pl, pr := q(l, r-1), q(l, l+1), q(l+1, l+2)33 if pl == pr {34 if p > pl {35 ans = pl - 136 return37 }38 ans = pl + 139 return40 }41 if pl == p {42 ans = 2*l + 1 - p43 return44 }45 ans = 2*l + 3 - p46 return47 }48 49 m := (l + r) >> 150 if l == ll && r == rr {51 if p < m {52 if pp := q(l, m-1); pp == p {53 r, rr = m, m54 } else {55 l, ll = m, p56 }57 } else {58 if pp := q(m, r-1); pp == p {59 l, ll = m, m60 } else {61 r, rr = m, p+162 }63 }64 } else if r == rr {65 if pp := q(ll, m-1); pp == p {66 r, rr = m, m67 } else {68 l = m69 }70 } else {71 if pp := q(m, rr-1); pp == p {72 l, ll = m, m73 } else {74 r = m75 }76 }77 }78}79 80func ioq86() {81 in := os.Stdin82 out := os.Stdout83 84 Q := func(req req86) (resp resp86) {85 Fprintln(out, "?", req.l, req.r)86 87 Fscan(in, &resp.v)88 return89 }90 91 d := input86{}92 Fscan(in, &d.n)93 gs := CF1486C2(d, Q)94 ans := gs.ans95 Fprintln(out, "!", ans)96 97}98 99100