Approach
Stack-based processing
For Codeforces 796C — Bank Hacking, 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
- 92 lines of Go from the credited upstream file 796C.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 "math"9 "sort"10)11 1213func CF796C(_r io.Reader, out io.Writer) {14 in := bufio.NewReader(_r)15 min := func(a, b int) int {16 if a > b {17 return b18 }19 return a20 }21 max := func(a, b int) int {22 if b > a {23 return b24 }25 return a26 }27 28 var n, v, w int29 Fscan(in, &n)30 a := make([]int, n)31 for i := range a {32 Fscan(in, &a[i])33 }34 g := make([][]int, n)35 for i := 1; i < n; i++ {36 Fscan(in, &v, &w)37 v--38 w--39 g[v] = append(g[v], w)40 g[w] = append(g[w], v)41 }42 43 ans := math.MaxInt44 h := lazyHeap{append(a[:0:0], a...), map[int]int{}}45 heap.Init(&h)46 for i, v := range a {47 mx := v48 h.delete(v)49 for _, w := range g[i] {50 mx = max(mx, a[w]+1)51 h.delete(a[w])52 }53 h.do()54 if h.Len() > 0 {55 mx = max(mx, h.IntSlice[0]+2)56 }57 ans = min(ans, mx)58 h.push(v)59 for _, w := range g[i] {60 h.push(a[w])61 }62 }63 Fprint(out, ans)64}65 6667 68type lazyHeap struct {69 sort.IntSlice70 lazy map[int]int71}72 73func (h lazyHeap) Less(i, j int) bool { return h.IntSlice[i] > h.IntSlice[j] }74func (h *lazyHeap) Push(v any) { h.IntSlice = append(h.IntSlice, v.(int)) }75func (h *lazyHeap) Pop() any { a := h.IntSlice; v := a[len(a)-1]; h.IntSlice = a[:len(a)-1]; return v }76func (h *lazyHeap) push(v int) {77 if h.lazy[v] > 0 {78 h.lazy[v]--79 } else {80 heap.Push(h, v)81 }82}83func (h *lazyHeap) do() {84 for h.Len() > 0 && h.lazy[h.IntSlice[0]] > 0 {85 h.lazy[h.IntSlice[0]]--86 heap.Pop(h)87 }88}89func (h *lazyHeap) pop() int { h.do(); return heap.Pop(h).(int) }90func (h *lazyHeap) top() int { h.do(); return h.IntSlice[0] }91func (h *lazyHeap) delete(v int) { h.lazy[v]++ }92