Problem solution · Go

Codeforces 1251E2 — Voting (Hard Version)

Codeforces 1251E2 — Voting (Hard Version): a Go solution using stack-based processing. Learn the idea, check the complexity, and read the full code, with credit to EndlessCheng Codeforces Go.

Technique
Stack-based processing
Source
EndlessCheng Codeforces Go
Length
46 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

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.

  1. Define what every stack entry represents.
  2. Pop entries once the current item resolves or invalidates them.
  3. 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.

Source

Code and credit

This code comes from EndlessCheng Codeforces Go by Σndless (EndlessCheng) and is used under the MIT licence.

Full codeCodeforces 1251E2 — Voting (Hard Version) · GoGo
Use this to learn the idea, then write your own version.
package main import (	"bufio"	"container/heap"	. "fmt"	"io"	"sort") // github.com/EndlessCheng/codeforces-gotype hp51 struct{ sort.IntSlice } func (h *hp51) Push(v interface{}) { h.IntSlice = append(h.IntSlice, v.(int)) }func (h *hp51) Pop() interface{}   { a := h.IntSlice; v := a[len(a)-1]; h.IntSlice = a[:len(a)-1]; return v } func CF1251E2(_r io.Reader, _w io.Writer) {	in := bufio.NewReader(_r)	out := bufio.NewWriter(_w)	defer out.Flush() 	var T, n int	for Fscan(in, &T); T > 0; T-- {		Fscan(in, &n)		a := make([]struct{ m, p int }, n)		for i := range a {			Fscan(in, &a[i].m, &a[i].p)		}		// 按 (mi,pi) 排序,然后把 (i,mi) 画在平面直角坐标系上		// 初始时,在 y=x 直线下方的点都可以视作是「免费」的,如果有不能免费的点,应考虑从最后一个不能免费的到末尾这段中的最小 pi,然后将 y=x 抬高成 y=x+1 继续比较		// 维护最小 pi 可以用最小堆		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 })		ans := int64(0)		for i, buy, h := n-1, 0, new(hp51); i >= 0; i-- {			heap.Push(h, a[i].p)			if a[i].m > i+buy {				buy++				ans += int64(heap.Pop(h).(int))			}		}		Fprintln(out, ans)	}} //func main() { CF1251E2(os.Stdin, os.Stdout) } 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗