Approach
Stack-based processing
For Codeforces 1486E — Paired Payment, 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
- 81 lines of Go from the credited upstream file 1486E.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)9 1011type pair86 struct{ v, d int }12type hp86 []pair8613 14func (h hp86) Len() int { return len(h) }15func (h hp86) Less(i, j int) bool { return h[i].d < h[j].d }16func (h hp86) Swap(i, j int) { h[i], h[j] = h[j], h[i] }17func (h *hp86) Push(v interface{}) { *h = append(*h, v.(pair86)) }18func (h *hp86) Pop() (v interface{}) { a := *h; *h, v = a[:len(a)-1], a[len(a)-1]; return }19func (h *hp86) push(v pair86) { heap.Push(h, v) }20func (h *hp86) pop() pair86 { return heap.Pop(h).(pair86) }21 22func CF1486E(_r io.Reader, _w io.Writer) {23 in := bufio.NewReader(_r)24 out := bufio.NewWriter(_w)25 defer out.Flush()26 const inf int = 1e927 type nb struct{ to, wt int }28 29 var n, m, v, w, wt int30 Fscan(in, &n, &m)31 g := make([][]nb, n)32 for i := 0; i < m; i++ {33 Fscan(in, &v, &w, &wt)34 v--35 w--36 g[v] = append(g[v], nb{w, wt})37 g[w] = append(g[w], nb{v, wt})38 }39 dist := make([]int, n)40 mi := make([]int, n)41 for i := range dist {42 dist[i] = inf43 mi[i] = inf44 }45 dist[0] = 046 q := hp86{{}}47 for len(q) > 0 {48 p := q.pop()49 v := p.v50 if p.d > dist[v] {51 continue52 }53 for _, e := range g[v] {54 w := e.to55 56 57 58 59 if e.wt >= mi[w] {60 continue61 }62 mi[w] = e.wt63 for _, e2 := range g[w] {64 u := e2.to65 if newD := dist[v] + (e.wt+e2.wt)*(e.wt+e2.wt); newD < dist[u] {66 dist[u] = newD67 q.push(pair86{u, newD})68 }69 }70 }71 }72 for _, v := range dist {73 if v == inf {74 v = -175 }76 Fprint(out, v, " ")77 }78}79 8081