Approach
Stack-based processing
For Codeforces 1732D2 — Balance (Hard version), the implementation keeps unresolved items in last-in, first-out order, often to match boundaries, parse structure, or maintain monotonic candidates.
- Define what every stack entry represents.
- Pop entries once the current item resolves or invalidates them.
- Push the current item with only the information later steps need.
Code notes
- 74 lines of Go from the credited upstream file 1732D2.go.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
If each item is pushed and popped at most once, the stack work is linear.
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 "container/heap"6 . "fmt"7 "io"8 "sort"9)10 1112func cf1732D2(_r io.Reader, _w io.Writer) {13 in := bufio.NewReader(_r)14 out := bufio.NewWriter(_w)15 defer out.Flush()16 17 var q, x int18 var op string19 Fscan(in, &q)20 mex := map[int]int{}21 has := map[int]bool{}22 belong := map[int][]*lazyHeap32{}23 missHs := map[int]*lazyHeap32{}24 for ; q > 0; q-- {25 Fscan(in, &op, &x)26 if op == "+" {27 has[x] = true28 for _, miss := range belong[x] {29 miss.toDel[x] = true30 }31 } else if op == "-" {32 delete(has, x)33 for _, miss := range belong[x] {34 if miss.toDel[x] {35 delete(miss.toDel, x)36 } else {37 heap.Push(miss, x)38 }39 }40 } else {41 if missHs[x] == nil {42 missHs[x] = &lazyHeap32{[]int{}, map[int]bool{}}43 }44 miss := missHs[x]45 for miss.Len() > 0 && miss.toDel[miss.IntSlice[0]] {46 delete(miss.toDel, miss.IntSlice[0])47 heap.Pop(miss)48 }49 if miss.Len() > 0 {50 Fprintln(out, miss.IntSlice[0])51 continue52 }53 if mex[x] == 0 {54 mex[x] = x55 }56 for has[mex[x]] {57 belong[mex[x]] = append(belong[mex[x]], miss)58 mex[x] += x59 }60 Fprintln(out, mex[x])61 }62 }63}64 6566 67type lazyHeap32 struct {68 sort.IntSlice69 toDel map[int]bool70}71 72func (h *lazyHeap32) Push(v any) { h.IntSlice = append(h.IntSlice, v.(int)) }73func (h *lazyHeap32) Pop() any { a := h.IntSlice; v := a[len(a)-1]; h.IntSlice = a[:len(a)-1]; return v }74