Approach
Stack-based processing
For Codeforces 1239C — Queue in the Train, 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
- 56 lines of Go from the credited upstream file 1239C.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 1112type hp39 struct{ sort.IntSlice }13 14func (h *hp39) Push(v interface{}) { h.IntSlice = append(h.IntSlice, v.(int)) }15func (h *hp39) Pop() interface{} { a := h.IntSlice; v := a[len(a)-1]; h.IntSlice = a[:len(a)-1]; return v }16func (h *hp39) push(v int) { heap.Push(h, v) }17func (h *hp39) pop() int { return heap.Pop(h).(int) }18 19func CF1239C(_r io.Reader, out io.Writer) {20 in := bufio.NewReader(_r)21 var n int22 var t int6423 Fscan(in, &n, &t)24 a := make([]struct{ t, i int }, n)25 for i := range a {26 Fscan(in, &a[i].t)27 a[i].i = i28 }29 sort.Slice(a, func(i, j int) bool { a, b := a[i], a[j]; return a.t < b.t || a.t == b.t && a.i < b.i })30 31 ans := make([]interface{}, n)32 q, w := []int{}, hp39{}33 for left, i, cur := n, 0, int64(0); left > 0; left-- {34 if len(q) == 0 {35 if len(w.IntSlice) > 0 {36 q = append(q, w.pop()) 37 } else {38 cur = int64(a[i].t)39 }40 }41 cur += t42 for ; i < n && int64(a[i].t) <= cur; i++ {43 if i := a[i].i; len(q) == 0 || i < q[len(q)-1] {44 q = append(q, i)45 } else {46 w.push(i)47 }48 }49 ans[q[0]] = cur50 q = q[1:]51 }52 Fprintln(out, ans...)53}54 5556