- 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
- 108 lines of Go from the credited upstream file 1000F.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 "math"8 "sort"9)10 1112func CF1000F(_r io.Reader, _w io.Writer) {13 out := bufio.NewWriter(_w)14 defer out.Flush()15 buf := make([]byte, 4096)16 _i := len(buf)17 rc := func() byte {18 if _i == len(buf) {19 _r.Read(buf)20 _i = 021 }22 b := buf[_i]23 _i++24 return b25 }26 ri := func() (x int) {27 b := rc()28 for ; '0' > b; b = rc() {29 }30 for ; '0' <= b; b = rc() {31 x = x*10 + int(b&15)32 }33 return34 }35 type query struct{ bid, l, r, idx int }36 37 n := ri()38 a := make([]int, n)39 for i := range a {40 a[i] = ri()41 }42 q := ri()43 qs := make([]query, q)44 blockSize := int(math.Round(math.Sqrt(float64(n))))45 for i := range qs {46 l := ri()47 qs[i] = query{l / blockSize, l, ri() + 1, i}48 }49 sort.Slice(qs, func(i, j int) bool {50 qi, qj := qs[i], qs[j]51 if qi.bid != qj.bid {52 return qi.bid < qj.bid53 }54 if qi.bid&1 == 0 {55 return qi.r < qj.r56 }57 return qi.r > qj.r58 })59 60 cnt := [5e5 + 1]int{}61 del := [5e5 + 1]int{} 62 s := []int{0} 63 update := func(i, d int) {64 v := a[i-1]65 if cnt[v] == 1 {66 del[v]++ 67 }68 cnt[v] += d69 if cnt[v] == 1 {70 71 if del[v] > 0 {72 del[v]--73 } else {74 s = append(s, v)75 }76 }77 }78 ans := make([]int, q)79 l, r := 1, 180 for _, q := range qs {81 for ; r < q.r; r++ {82 update(r, 1)83 }84 for ; l < q.l; l++ {85 update(l, -1)86 }87 for l > q.l {88 l--89 update(l, 1)90 }91 for r > q.r {92 r--93 update(r, -1)94 }95 96 for del[s[len(s)-1]] > 0 {97 del[s[len(s)-1]]--98 s = s[:len(s)-1]99 }100 ans[q.idx] = s[len(s)-1]101 }102 for _, v := range ans {103 Fprintln(out, v)104 }105}106 107108