Approach
Stack-based processing
For Codeforces 639D — Bear and Contribution, 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
- 49 lines of Go from the credited upstream file 639D.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 "slices"8 "sort"9)10 1112func cf639D(in io.Reader, out io.Writer) {13 var n, k, b, c int14 Fscan(in, &n, &k, &b, &c)15 b = min(b, c*5)16 t := make([]int, n)17 for i := range t {18 Fscan(in, &t[i])19 }20 slices.Sort(t)21 22 ans := int(1e18)23 for i := range 5 {24 T := int(2e9) + i25 h := &hp39{}26 heap.Init(h)27 sum := 028 for j := 0; j < n; j++ {29 nd := (T-t[j])/5*b + (T-t[j])%5*c30 sum += nd31 heap.Push(h, nd)32 if h.Len() > k {33 sum -= heap.Pop(h).(int)34 }35 if h.Len() == k {36 ans = min(ans, sum-(T-t[j])/5*b*k)37 }38 }39 }40 Fprint(out, ans)41}42 4344 45type hp39 struct{ sort.IntSlice }46func (h hp39) Less(i, j int) bool { return h.IntSlice[i] > h.IntSlice[j] }47func (h *hp39) Push(v any) { h.IntSlice = append(h.IntSlice, v.(int)) }48func (h *hp39) Pop() any { a := h.IntSlice; v := a[len(a)-1]; h.IntSlice = a[:len(a)-1]; return v }49