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.
- 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
- 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.
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 1112func CF1701D(_r io.Reader, _w io.Writer) {13 in := bufio.NewReader(_r)14 out := bufio.NewWriter(_w)15 defer out.Flush()16 17 var T, n, v int18 for Fscan(in, &T); T > 0; T-- {19 Fscan(in, &n)20 a01 = make([]struct{ l, r, i int }, n)21 for i := range a01 {22 Fscan(in, &v)23 a01[i].l = (i+1)/(v+1) + 124 if v > 0 {25 a01[i].r = (i + 1) / v26 } else {27 a01[i].r = n28 }29 a01[i].i = i30 }31 sort.Slice(a01, func(i, j int) bool { return a01[i].l < a01[j].l })32 ans := make([]int, n)33 h := hp01{}34 for i, j := 1, 0; i <= n; i++ {35 for ; j < n && a01[j].l == i; j++ {36 heap.Push(&h, j)37 }38 k := heap.Pop(&h).(int)39 ans[a01[k].i] = i40 }41 for _, v := range ans {42 Fprint(out, v, " ")43 }44 Fprintln(out)45 }46}47 4849 50var a01 []struct{ l, r, i int }51type hp01 struct{ sort.IntSlice }52func (h hp01) Less(i, j int) bool { return a01[h.IntSlice[i]].r < a01[h.IntSlice[j]].r }53func (h *hp01) Push(v interface{}) { h.IntSlice = append(h.IntSlice, v.(int)) }54func (h *hp01) Pop() interface{} { a := h.IntSlice; v := a[len(a)-1]; h.IntSlice = a[:len(a)-1]; return v }55