Approach
Stack-based processing
For Codeforces 1251E2 — Voting (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
- 46 lines of Go from the credited upstream file 1251E2.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 1112type hp51 struct{ sort.IntSlice }13 14func (h *hp51) Push(v interface{}) { h.IntSlice = append(h.IntSlice, v.(int)) }15func (h *hp51) Pop() interface{} { a := h.IntSlice; v := a[len(a)-1]; h.IntSlice = a[:len(a)-1]; return v }16 17func CF1251E2(_r io.Reader, _w io.Writer) {18 in := bufio.NewReader(_r)19 out := bufio.NewWriter(_w)20 defer out.Flush()21 22 var T, n int23 for Fscan(in, &T); T > 0; T-- {24 Fscan(in, &n)25 a := make([]struct{ m, p int }, n)26 for i := range a {27 Fscan(in, &a[i].m, &a[i].p)28 }29 30 31 32 sort.Slice(a, func(i, j int) bool { a, b := a[i], a[j]; return a.m < b.m || a.m == b.m && a.p < b.p })33 ans := int64(0)34 for i, buy, h := n-1, 0, new(hp51); i >= 0; i-- {35 heap.Push(h, a[i].p)36 if a[i].m > i+buy {37 buy++38 ans += int64(heap.Pop(h).(int))39 }40 }41 Fprintln(out, ans)42 }43}44 4546