- 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 1697D.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 "os"7 "sort"8 "strconv"9)10 1112type interaction97 interface {13 readInitData() initData9714 query(request97) response9715 printAnswer(answer97)16}17 18type stdIO97 struct {19 in *bufio.Reader20 out *bufio.Writer21}22 23type (24 initData97 struct{ n int }25 request97 struct{ q []int }26 response97 struct{ res string }27 answer97 struct{ ans string }28)29 30func (io stdIO97) readInitData() initData97 {31 in := io.in32 33 var n int34 Fscan(in, &n)35 36 return initData97{n}37}38 39func (io stdIO97) query(q request97) (resp response97) {40 in, out := io.in, io.out41 42 Fprint(out, "?")43 for _, v := range q.q {44 Fprint(out, " ", v)45 }46 Fprintln(out)47 48 out.Flush()49 50 Fscan(in, &resp.res)51 52 if resp.res == "0" {53 panic(-1)54 }55 return56}57 58func (io stdIO97) printAnswer(a answer97) {59 out := io.out60 61 Fprintln(out, "!", a.ans)62 63 out.Flush()64}65 66func doInteraction97(it interaction97) {67 dt := it.readInitData()68 n := dt.n69 70 getChar := func(i int) byte {71 return it.query(request97{[]int{1, i + 1}}).res[0]72 }73 getDiff := func(l, r int) int {74 v, _ := strconv.Atoi(it.query(request97{[]int{2, l + 1, r + 1}}).res)75 return v76 }77 78 ans := make([]byte, n)79 defer func() { it.printAnswer(answer97{string(ans)}) }()80 81 type pair struct {82 i int83 b byte84 }85 pos := []pair{}86 for i := range ans {87 j := sort.Search(len(pos), func(j int) bool { return getDiff(pos[j].i, i) > len(pos)-j }) - 188 if j < 0 {89 ans[i] = getChar(i)90 } else {91 ans[i] = pos[j].b92 pos = append(pos[:j], pos[j+1:]...)93 }94 pos = append(pos, pair{i, ans[i]})95 }96}97 98func run97() {99 in := bufio.NewReader(os.Stdin)100 out := bufio.NewWriter(os.Stdout)101 102 T := 1103 for ; T > 0; T-- {104 doInteraction97(stdIO97{in, out})105 }106}107 108109