Problem solution · Go

Codeforces 767E — Change-free

Codeforces 767E — Change-free: 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
55 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 767E — Change-free, 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

  • 55 lines of Go from the credited upstream file 767E.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 767E — Change-free · GoGo
Use this to learn the idea, then write your own version.
package main import (	"bufio"	"container/heap"	. "fmt"	"io") // https://github.com/EndlessChengfunc cf767E(in io.Reader, _w io.Writer) {	out := bufio.NewWriter(_w)	defer out.Flush()	var n, coin, w, sum int	Fscan(in, &n, &coin)	c := make([]int, n)	for i := range c {		Fscan(in, &c[i])	} 	ans := make([]pair67, n)	h := hp67{}	for i, c := range c {		Fscan(in, &w)		r := c % 100		ans[i] = pair67{c / 100, r}		if r == 0 {			continue		}		coin -= r		heap.Push(&h, pair67{w * (100 - r), i})		if coin < 0 {			p := heap.Pop(&h).(pair67)			sum += p.v			ans[p.i].v++			ans[p.i].i = 0			coin += 100		}	} 	Fprintln(out, sum)	for _, p := range ans {		Fprintln(out, p.v, p.i)	}} //func main() { cf767E(bufio.NewReader(os.Stdin), os.Stdout) }type pair67 struct{ v, i int }type hp67 []pair67func (h hp67) Len() int           { return len(h) }func (h hp67) Less(i, j int) bool { return h[i].v < h[j].v }func (h hp67) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }func (h *hp67) Push(v any)        { *h = append(*h, v.(pair67)) }func (h *hp67) Pop() any          { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } 

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 ↗