Problem solution · Go

Codeforces 1887C — Minimum Array

Codeforces 1887C — Minimum Array: 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
66 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 1887C — Minimum Array, 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

  • 66 lines of Go from the credited upstream file 1887C.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 1887C — Minimum Array · GoGo
Use this to learn the idea, then write your own version.
package main import (	"bufio"	"container/heap"	. "fmt"	"io"	"sort") // https://github.com/EndlessChengfunc cf1887C(in io.Reader, _w io.Writer) {	out := bufio.NewWriter(_w)	defer out.Flush()	var T, n, q, l, r, x int	for Fscan(in, &T); T > 0; T-- {		Fscan(in, &n)		a := make([]int, n)		for i := range a {			Fscan(in, &a[i])		} 		sd := make([]int, n+1)		d := make([]int, n+1)		h := hp87{}		Fscan(in, &q)		for range q {			Fscan(in, &l, &r, &x)			if x == 0 {				continue			}			l--			if d[l] == 0 {				heap.Push(&h, l)			}			d[l] += x			if d[r] == 0 {				heap.Push(&h, r)			}			d[r] -= x			for h.Len() > 0 && d[h.IntSlice[0]] == 0 {				heap.Pop(&h)			}			if h.Len() > 0 && d[h.IntSlice[0]] < 0 {				for _, i := range h.IntSlice {					sd[i] += d[i]					d[i] = 0				}				h.IntSlice = h.IntSlice[:0]			}		} 		s := 0		for i, v := range a {			s += sd[i]			Fprint(out, v+s, " ")		}		Fprintln(out)	}} //func main() { cf1887C(bufio.NewReader(os.Stdin), os.Stdout) }type hp87 struct{ sort.IntSlice }func (h *hp87) Push(v any) { h.IntSlice = append(h.IntSlice, v.(int)) }func (h *hp87) Pop() any   { a := h.IntSlice; v := a[len(a)-1]; h.IntSlice = 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 ↗