Problem solution · Go

Codeforces 1701D — Permutation Restoration

Codeforces 1701D — Permutation Restoration: 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 1701D — Permutation Restoration, 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 1701D.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 1701D — Permutation Restoration · 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-gofunc CF1701D(_r io.Reader, _w io.Writer) {	in := bufio.NewReader(_r)	out := bufio.NewWriter(_w)	defer out.Flush() 	var T, n, v int	for Fscan(in, &T); T > 0; T-- {		Fscan(in, &n)		a01 = make([]struct{ l, r, i int }, n)		for i := range a01 {			Fscan(in, &v)			a01[i].l = (i+1)/(v+1) + 1			if v > 0 {				a01[i].r = (i + 1) / v			} else {				a01[i].r = n			}			a01[i].i = i		}		sort.Slice(a01, func(i, j int) bool { return a01[i].l < a01[j].l })		ans := make([]int, n)		h := hp01{}		for i, j := 1, 0; i <= n; i++ {			for ; j < n && a01[j].l == i; j++ {				heap.Push(&h, j)			}			k := heap.Pop(&h).(int)			ans[a01[k].i] = i		}		for _, v := range ans {			Fprint(out, v, " ")		}		Fprintln(out)	}} //func main() { CF1701D(os.Stdin, os.Stdout) } var a01 []struct{ l, r, i int }type hp01 struct{ sort.IntSlice }func (h hp01) Less(i, j int) bool  { return a01[h.IntSlice[i]].r < a01[h.IntSlice[j]].r }func (h *hp01) Push(v interface{}) { h.IntSlice = append(h.IntSlice, v.(int)) }func (h *hp01) Pop() interface{}   { 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 ↗