Approach
Stack-based processing
For Codeforces 899E — Segments Removal, 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
- 79 lines of Go from the credited upstream file 899E.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 "container/heap"5 . "fmt"6 "io"7)8 910func cf899E(in io.Reader, out io.Writer) {11 var n, ans int12 Fscan(in, &n)13 14 pre := make([]int, n)15 nxt := make([]int, n)16 sz := make([]int, n)17 for i := range n {18 pre[i] = i - 119 nxt[i] = i + 120 sz[i] = 121 }22 del := func(i int) {23 l, r := pre[i], nxt[i]24 if l >= 0 {25 nxt[l] = r26 }27 if r < n {28 pre[r] = l29 }30 }31 merge := func(from, to int) {32 sz[to] += sz[from]33 sz[from] = 034 del(from)35 }36 37 a := make([]int, n)38 for i := range a {39 Fscan(in, &a[i])40 if i > 0 && a[i] == a[i-1] {41 merge(i-1, i)42 }43 }44 45 h := hp99{}46 for i, s := range sz {47 if s > 0 {48 heap.Push(&h, pair99{s, i})49 }50 }51 52 for len(h) > 0 {53 p := heap.Pop(&h).(pair99)54 i := p.i55 if sz[i] != p.sz {56 continue57 }58 sz[i] = 059 l, r := pre[i], nxt[i]60 del(i)61 if l >= 0 && r < n && a[l] == a[r] {62 merge(l, r)63 heap.Push(&h, pair99{sz[r], r})64 }65 ans++66 }67 Fprint(out, ans)68}69 7071 72type pair99 struct{ sz, i int }73type hp99 []pair9974func (h hp99) Len() int { return len(h) }75func (h hp99) Less(i, j int) bool { return h[i].sz > h[j].sz || h[i].sz == h[j].sz && h[i].i < h[j].i }76func (h hp99) Swap(i, j int) { h[i], h[j] = h[j], h[i] }77func (h *hp99) Push(v any) { *h = append(*h, v.(pair99)) }78func (h *hp99) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v }79